I entered the following code (and had no compiling problems or anything):
float y = 5/2;
printf("%f\n", y);
The output was simply: 2.00000
My math isn't wrong is it? Or am I wrong on the / operator? It means divide doesn't it? And 5/2 should equal 2.5?
Any help is greatly appreciated!
5
is an int
and 2
is an int
. Therefore, 5/2
will use integer division. If you replace 5
with 5.0f
(or 2
with 2.0f
), making one of the int
s a float
, you will get floating point division and get the 2.5
you expect. You can also achieve the same effect by explicitly casting either the numerator or denominator (e.g. ((float) 5) / 2
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With