我在使用 float 时遇到了一些奇怪的舍入行为。下面的代码演示了这个问题。解决这个问题的最佳方法是什么?我一直在寻找解决方案,但运气不佳。
#include<stdio.h>
int main(void)
{
float t;
t = 5592411;
printf("%f\n", 1.5*t);
t *= 1.5;
printf("%f\n", t);
return 0;
}
上面的代码应该打印出相同的值,但我在使用 GCC 4.7.2 的设置中得到了这个值:
8388616.500000
8388616.000000
如果我使用计算器,我会得到第一个值,所以我假设第二个值以某种方式四舍五入。我有相同的 Fortran 代码,它不对值进行舍入(具有 0.5)。
最佳答案
1.5
是一个 double
常量而不是一个 float
并且 C 有自动升级规则。因此,当您执行 1.5*t
时,发生的是 (i) t
转换为 double
; (ii) double
乘以 double
1.5
; (iii) double
被打印(因为 %f
是 double
的格式化程序)。
相反,t *= 1.5
将 t
提升为 double ,执行 double 乘法,然后截断结果以将其存储回 [单精度] float
。
要获得证据,请尝试:
float t;
t = 5592411;
printf("%f\n", 1.5f*t); // multiply a float by a float, for no promotion
t *= 1.5;
printf("%f\n", t);
return 0;
或者:
double t; // store our intermediate results in a double
t = 5592411;
printf("%f\n", 1.5f*t);
t *= 1.5;
printf("%f\n", t);
return 0;
关于c - C中的浮点舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15798338/