Because they are, for most purposes, more accurate than integers.
Now how is that? "for speed of an object in a game..." this is a good example for such a case. Say you need to have some very fast objects, like bullets. To be able to describe their motion with integer speed variables, you need to make sure the speeds are in the range of the integer variables, that means you cannot have an arbitrarily fine raster.
But then, you might also want to describe some very slow objects, like the hour hand of a clock. As this is about 6 orders of magnitude slower than the bullet objects, the first ld(10⁶) ≈ 20 bits are zero, that rules out short int
types from the start. Ok, today we have long
s everywhere, which leave us with a still-comfortable 12 bits. But even then, the clock speed will be exact to only to four decimal places. That's not a very good clock... but it's certainly ok for a game. Just, you would not want to make the raster much coarser than it already is.
...which leads to problems if some day you should like to introduce a new, even faster type of object. There is no "headroom" left.
What happens if we choose a float type? Same size of 32 bits, but now you have a full 24 bits of precision, for all objects. That means, the clock has enough precision to stay in sync up-to-the-seconds for years. The bullets have no higher precision, but they only "live" for fractions of a second anyway, so it would be utterly useless if they had. And you do not get into any kind of trouble if you want to describe even much faster objects (why not speed of light? No problem) or much slower ones. You certainly won't need such things in a game, but you sometimes do in physics simulations.
And with floating-point numbers, you get this same precision always and without first having to cleverly choose some non-obvious raster. That is perhaps the most important point, as such choice necessities are very error-prone.
No, it's a bad habit. When you do this for a living, you'll likely end up violating style guides that your team adheres to (or at least get whacked during code reviews).
Yes it works, but if there's a c++ equivalent, use it. (e.g. try not to mix printfs
with couts
)
Best Answer
The default choice for a floating-point type should be
double
. This is also the type that you get with floating-point literals without a suffix or (in C) standard functions that operate on floating point numbers (e.g.exp
,sin
, etc.).float
should only be used if you need to operate on a lot of floating-point numbers (think in the order of thousands or more) and analysis of the algorithm has shown that the reduced range and accuracy don't pose a problem.long double
can be used if you need more range or accuracy thandouble
, and if it provides this on your target platform.In summary,
float
andlong double
should be reserved for use by the specialists, withdouble
for "every-day" use.