I am new to C and have the following simple code snippet exploring C limitations:
int main() {
float x = 2147483000;
int y = static_cast<int>(x);
cout << "x: " << x << ", y: " << y;
}
Why is the output showing me different values for x & y even though the float value is within int limit which is 2147483647
Code Results
x: 2.14748e 09, y: 2147483008
Why is it showing different values for x & y?
CodePudding user response:
I have read your question carefully. There is a misconception, not mistake.
That is happening because the float have a certain capacity to store its precision up to 7 decimal places if the digits exceeds than the 7th digit, It would loss its precision after the 7th digit for beyond to it. Due to this reason the output is not accurate or same.
CodePudding user response:
Why is it showing different values for x & y?
The default conversion for displaying float
that are in the range for which an exponent is used for display is to show six significant digits.
In the format commonly used for float
, IEEE-754 binary32, the two representable values nearest 2,147,483,000 are 2,147,482,880 and 2,147,483,008. So, for float x = 2147483000;
, a good C implementation will convert 2,147,483,000 to the closest float
value, 2,147,483,008.
Then int y = static_cast<int>(x);
sets y
to this same value, 2,147,483,008.
When the float
x
is inserted into the cout
stream with default formatting, six significant digits are used, producing 2.14748•109.
When the int
y
is inserted into the stream, its full value is shown, 2,147,483,008.
You can see the full value by requesting more precision. std::cout << std::setprecision(99) << "x: " << x << ", y: " << y << '\n';
produces “x: 2147483008, y: 2147483008”.