Reputation: 69
float x = 2.5;
int i = (int)x;
We all know the result is 2, but I want to know why we get this result, what is the theory and how the system work? Can it be explained using binary form (IEEE)?
Upvotes: 1
Views: 80
Reputation: 206577
This is specified in the C++ Standard (Draft Standard N3337)
4.9 Floating-integral conversions
1 A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. [ Note: If the destination type is bool, see 4.12. — end note ]
Upvotes: 1
Reputation: 145269
C++11 §4.9/1:
” The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.
That’s it, the theory of it: because the standard says so.
It's a reasonable language design choice but by no means the only possible reasonable choice.
Upvotes: 2