C++:如何将双精度舍入为整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9695329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:10:37  来源:igfitidea点击:

C++: How to round a double to an int?

c++floating-pointrounding

提问by midnightBlue

I have a double (call it x), meant to be 55 but in actuality stored as 54.999999999999943157 which I just realised.

我有一个double(称为x),本来是55,但实际上存储为54.999999999999943157,我刚刚意识到。

So when I do

所以当我做

double x = 54.999999999999943157;
int y = (int) x;

y = 54 instead of 55!

y = 54 而不是 55!

This puzzled me for a long time. How do I get it to correctly round?

这让我困惑了很长时间。我如何让它正确舍入?

回答by Moritz

add 0.5 before casting (if x > 0) or subtract 0.5 (if x < 0), because the compiler will always truncate.

在强制转换之前加 0.5(如果 x > 0)或减去 0.5(如果 x < 0),因为编译器总是会截断。

float x = 55; // stored as 54.999999...
x = x + 0.5 - (x<0); // x is now 55.499999...
int y = (int)x; // truncated to 55

C++11 also introduces std::round, which likely uses a similar logic of adding 0.5 to |x| under the hood (see the link if interested) but is obviously more robust.

C++11 还引入了std::round,它可能使用类似的逻辑将 0.5 添加到 |x| 在引擎盖下(如果有兴趣,请参阅链接)但显然更强大。

A follow up question might be whythe float isn't stored as exactly 55. For an explanation, see thisstackoverflow answer.

一个后续问题可能是为什么浮点数没有准确存储为 55。有关解释,请参阅stackoverflow 答案。

回答by MK.

Casting is not a mathematical operation and doesn't behave as such. Try

铸造不是数学运算,也不是这样的。尝试

int y = (int)round(x);

回答by Pubby

Casting to an inttruncates the value. Adding 0.5causes it to do proper rounding.

转换为 an 会int截断该值。添加0.5会导致它进行适当的舍入。

int y = (int)(x + 0.5);

回答by Pubby

It is worth noting that what you're doing isn't rounding, it's casting. Casting using (int) xtruncates the decimal value of x. As in your example, if x = 3.9995, the .9995gets truncated and x = 3.

值得注意的是,您所做的不是四舍五入,而是铸造。使用(int) x强制转换会截断 的十进制值x。在您的示例中,如果x = 3.9995.9995则被截断,而x = 3.

As proposed by many others, one solution is to add 0.5to x, and then cast.

正如许多其他人提出的那样,一种解决方案是添加0.5x,然后进行强制转换。

回答by zik

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double x=54.999999999999943157;
    int y=ceil(x);//The ceil() function returns the smallest integer no less than x
    return 0;
}