c++ help

Concentric

Expert Member
Joined
Feb 16, 2017
Messages
1,028
Reaction score
197
if i have:
float x;
x=2/5;
the value of x is given as 0.
but if x=2.0/5.0 then x=0.4
why?
I tested a couple other fractions without .0 and it seems like the numerator must be greater than the denominator otherwise a value of 0 is returned.why is this so?
Thanks
 
If you just use a number (like 2 instead of 2.0) then the compiler assumes an int. It then does the math, and only the result is casted to a float. And (int)2 / (int)5 is 0.
 
if i have:
float x;
x=2/5;
the value of x is given as 0.
but if x=2.0/5.0 then x=0.4
why?
I tested a couple other fractions without .0 and it seems like the numerator must be greater than the denominator otherwise a value of 0 is returned.why is this so?
Thanks

basically it sees 2 and 5 and they are integers and does an integer division to get you 0.
2.0 and 5.0 are floats so it does a float division and you get your expected result.
 
basically it sees 2 and 5 and they are integers and does an integer division to get you 0.
2.0 and 5.0 are floats so it does a float division and you get your expected result.

And to add to this, float will also round the number off (the whole number in your example) whereas a double will give you a more precise value.
 
basically it sees 2 and 5 and they are integers and does an integer division to get you 0.
2.0 and 5.0 are floats so it does a float division and you get your expected result.

2.0 and 5.0 are actually doubles (the f suffix, 2.0f and 5.0f needs to be specified to make it a float division), and will be the result of a double division, which is then cast to a single precision number. The division will almost certainly be done at compile time though - this is more relevant if one of the values is a variable.
 
And to add to this, float will also round the number off (the whole number in your example) whereas a double will give you a more precise value.

A double does give a more precise value as you say, but it also rounds the value off since it cannot represent 0.4 exactly either. I don't know what you meant by whole number, but 2 and 5 can both be represented by both floats and doubles exactly (without rounding to something different).
 
Top
Sign up to the MyBroadband newsletter
X