#include <stdio.h>
#include <float.h>
#include <stdlib.h>
int main() {
float x = 3.8, y = 5.2;
int a, b, c;
float d = x + y;
a = d;
b = (int)(x + y);
c = (int)(3.8 + 5.2);
printf("a=%d,b=%d,c=%d\n", a, b, c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果是
Run Code Online (Sandbox Code Playgroud)9,8,9
我认为9,9,9是正确的输出,请告诉我,为什么.
在单精度IEEE754(float最有可能在您的平台上使用的方案)中,x是3.7999999523162841796875和y现在5.19999980926513671875.这些的总和略低于9,并且演员要int截断结果.(注意,float x = 3.8实际上将double常量截断3.8为float:3.8f是类型的常量float.)
但是3.8 + 5.2以双精度计算.在双精度IEEE754 3.8是3.79999999999999982236431605997495353221893310546875和5.2是5.20000000000000017763568394002504646778106689453125.这总和刚刚超过9,因此int截断恢复9.
这一事实a,并b有不同的是,由于不是浮点评价严你的编译器.您应该可以根据需要更改其设置.
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |