#include <stdio.h>
double metersToFeet(double meters)
{
return meters / 0.3048;
}
int main()
{
printf("%u\n", (unsigned char)(char)(45.72 / 0.3048));
printf("%u\n", (unsigned char)(char)metersToFeet(45.72));
return 0;
}
This program outputs (on both GCC and Clang):
127
150
Why am I getting two different numbers?
The real answer (150) exceeds the range of a char
(on a normal system) if it's signed. This conversion invokes undefined behaviour; the compiler is free to do whatever it likes.
From the C99 standard, 6.3.1.4:
When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With