It's because by default cout has a precision of 6 digits (think of it as 6 sig-figs). [At least on my system, I'm not sure if that is dictated by the standard]
One possible way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
#include <iomanip>
int main()
{
using std::cout;
float f = 0.0111;
int i = 1010;
float f2 = i + f;
cout.precision(8); // 8 digits (including the left-hand side of decimal)
cout << f2;
}
[Not to confuse you too much, but note that floating-point numbers are inherently inexact most of the time.
0.0111 cannot be stored exactly as a floating-point number.]
If you need precise and all significant digits, for example for money, then you use (large enough) integer type and format the output to "human units":
1 2 3 4 5 6 7 8 9
#include <iostream>
#include <iomanip>
int main()
{
int i { 10100111 }; // in cents
std::cout << '$' << i/100 << '.' << std::setw(2) << std::setfill('0') << i%100 << '\n';
}
@hexfffff, would you like to tell us the background to your problem?
Is there any special significance to the fact that your example contains only 0's and 1's?
If you want to maintain such exactitude of decimal representations then you would have to work entirely with strings, and code up some fancy arithmetic operations of your own. It would probably make a nice exercise with classes ...
to a point you can store it as 2 integers, the fraction and the whole parts, where it is understood that the fractional part is divided by some constant (probably a power of 10 for beginners, eg 1 million).
smaller values, and this is relative, can be put in a single integer via the same idea where every number is understood to be divided by some constant, eg pi might be 3141592654 as a 64 bit int, or as 2 ints (3 and 141592654) ... see?
once the 2 integer approach runs dry, you can cook up a big-double class thingy.