...
When compiled with GCC 4.3.2 on Linux, this program prints the value -46
.
Compliant Solution
While not a portable solution, you can improve precision by using double
instead of float
This solution replaces the float
with a double
. Furthermore, it uses a static assertion (see DCL03-C. Use a static assertion to test the value of a constant expression) to guarantee that the double
type can represent any int
without loss of precision.
Code Block | ||
---|---|---|
| ||
#include <stdio.h> #include <float.h> /* define or include a definition of static_assert */ static_assert(sizeof(int) * 8 <= DBL_MANT_DIG); // 8 = bits / char int main() { int big = 1234567890; double approx = big; printf("%d\n", (big - (int)approx)); return 0; } |
...