float - c数据类型

wan*_*arn 3 c floating-point types floating-point-precision

int main() {
float a = 20000000;
float b = 1;
float c = a+b;

if (c==a) { printf("equal"); }

else { printf("not equal");}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我跑这个时,它说"平等".但当我将a的值更改为2000000(少一个零)时答案是否定的.为什么?

Dan*_*her 7

通常,a float具有24位的精度.数字20000001 = 0x1312d01需要精确表示25位,因此必须舍入.两个可表示值之间正好中间值的正常舍入模式是舍入到最后一位零,因此20000001舍入为20000000作为a float.

2000001 = 0x1e8481需要少于24位(21),因此不需要舍入.