Whats Wrong with the fraction part

#include<iostream>
using namespace std;
main()
{
float f;
cin>>f;
f -= int(f);
cout<<f;
}

Input 12345.12345
Expected Output 0.12345

Output 0.123047
Simple way to see 0.12345 in this case is to use the type double, but it may be useful to understand what happens:

12345.12345 is not a value that can be stored in a variable of type float. It lies between the two valid floats: 12345.123046875 and 12345.1240234375. Since it's closer to the first one, that's what cin >> f actually stores.

After subtracting 12345, you end up with 0.123046875, and since cout <<'s default precision is 6, you're seeing the output of 0.123047
You've just learned one of the magic limitations of floating-point arithmetic.

Change that float to a double and you should get better precision.

Hope this helps.
Woow thanks it works. But i wana know about how it works is there any book which explain limitations of floats or double in deep.
@ Cubbi what do you mean by
It lies between the two valid floats: 12345.123046875 and 12345.1240234375
wikipedia is fairly detailed.
float: http://en.wikipedia.org/wiki/Single_precision_floating-point_format
double: http://en.wikipedia.org/wiki/Double-precision_floating-point_format

what do you mean by
It lies between the two valid floats: 12345.123046875 and 12345.1240234375

Compare to int: the value 12345 is a value that can be stored in an int, the value 12346 is the next value that can be stored in an int. If you attempt to store 12345.2 in an int, it will be rounded and 12345 will be stored.

Same thing happens here, only with floats: you're trying to store 12345.12345, so it's rounded to 12345.123046875
Last edited on
Topic archived. No new replies allowed.