遇到问题在C四舍五入 [英] Having trouble rounding in c
问题描述
在试图找出如何圆一个浮点数像 1.255
到最近的百分之一,我发现了一些有趣的事情。我用gcc 4.4.5在Debian 6。
While trying to figure out how to round a float like 1.255
to the nearest hundredth, I found something interesting. I'm using gcc 4.4.5 on Debian 6.
int x = (1.255 * 100) + 0.5; // gives me back 125 instead of 126.
float y = (1.255 * 100) + 0.5; // gives me back 126.000000.
为什么是,当我保存到 INT
我回来 125
,而不是 126
?在Fedora当我保存上述前pression到 INT
我回来 126
。这是Debian的一个gcc的bug?任何帮助将大大AP preciated。
谢谢你。
Why is is that when I save to an int
I get back 125
and not 126
? In fedora when I save the above expression to an int
I get back 126
. Is this a gcc bug in debian ? Any help would be greatly appreciated.
Thanks.
推荐答案
虽然这看起来像一个典型的浮点问题,它比这更复杂。
Although this looks like a "typical" floating-point question, it's more complicated than that.
这其中涉及的3件事情的组合:
This one involves a combination of 3 things:
- 的通常浮点再presentation的东西。
- 隐式转换。
- 隐式类型推广。
让我们打破这:
浮点文本的类型双击
默认的。因此, 1.255
的类型为双击
。
Floating-point literals are of type double
by default. Hence 1.255
is of type double
.
因此,前pression:
Thus the expression:
(1.255 * 100) + 0.5
使用类型做双击
。
但由于二进制浮点无法重新present 1.255
正好,前pression计算结果为:
But because binary floating-point can't represent 1.255
exactly, the expression evaluates to:
(1.255 * 100) + 0.5 = 125.99999999999999000000
和类型是双击
。
由于这小于 126
,将其存储到一个整数,将导致 125
。
它存储到浮动
将其四舍五入到最接近的浮动
,这将导致 126
。
Since this is less than 126
, storing it to an integer will result in 125
.
Storing it to float
will round it to the nearest float
, which results in 126
.
int x = (1.255 * 100.) + 0.5;
float y = (1.255 * 100.) + 0.5;
double z = (1.255 * 100.) + 0.5;
cout << fixed;
cout << x << endl;
cout << setprecision(20) << y << endl;
cout << setprecision(20) << z << endl;
输出:
125
126.00000000000000000000
125.99999999999999000000
这篇关于遇到问题在C四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!