4
#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;
}

该程序输出(在 GCC 和 Clang 上):

127
150

为什么我得到两个不同的数字?

4

2 回答 2

8

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.

于 2013-06-05T00:17:07.840 回答
5

45.72 / 0.3048 is 150.

Type char on your platform is apparently a 8-but signed type. 150 is out of range for that type. This means that the behavior is undefined. The rest follows.

For example, I'm getting 127 127 in GCC through ideone.com, and 150 150 in MSVC. You got 127 150, which is amusing, but not surprising.

于 2013-06-05T00:20:03.760 回答