浮点四舍五入用C [英] Floating point rounding in C
问题描述
我碰到的花车一些奇怪的舍入行为。下面的code演示了此问题。什么是解决这个问题的最好方法?我一直在寻找解决方案,但还没有多少运气。
I've run into some weird rounding behaviour with floats. The code below demonstrates the problem. What is the best way to solve this? I've been looking for solutions but haven't had much luck.
#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;
}
在code以上应打印出相同的价值,但我得到这个使用我的设置GCC 4.7.2:
The code above should print out the same value, but I get this on my setup using GCC 4.7.2:
8388616.500000
8388616.500000
8388616.000000
8388616.000000
如果我用一个计算器,我得到的第一个值,所以我想第二个被莫名其妙地四舍五入。我有相同的Fortran code不四舍五入值(有0.5)。
If I use a calculator, I get the first value, so I assume the second is being rounded somehow. I have identical Fortran code which does not round the value(has the 0.5).
推荐答案
1.5
是双击
不变,而不是一个浮动
和C具有自动升级规则。所以,当你执行 1.5 * T
发生的事情是(我) T
转换为双
; (ii)该双击
被乘以双击
1.5
;及(iii)在双击
打印(如%F
是一个格式化双
)。
1.5
is a double
constant rather than a float
and C has automatic promotion rules. So when you perform 1.5*t
what happens is (i) t
is converted to a double
; (ii) that double
is multiplied by the double
1.5
; and (iii) the double
is printed (as %f
is the formatter for a double
).
相反, T * = 1.5
推动 T
来双,执行双乘法,然后截断结果将它存储回一个[单一precision] 浮动
。
Conversely, t *= 1.5
promotes t
to a double, performs a double multiplication and then truncates the result to store it back into a [single precision] float
.
有关证据,无论是尝试:
For evidence, try either:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!