C++ 中的 Round() 在哪里?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/554204/
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 15:56:15  来源:igfitidea点击:

Where is Round() in C++?

c++rounding

提问by Jason Punyon

Duplicate of: round() for float in C++

重复:round() 用于 C++ 中的浮点数



I'm using VS2008 and I've included math.h but I still can't find a round function. Does it exist?

我正在使用 VS2008 并且我已经包含了 math.h 但我仍然找不到圆形函数。它存在吗?

I'm seeing a bunch of "add 0.5 and cast to int" solutions on google. Is that the best practice?

我在谷歌上看到了一堆“添加 0.5 并转换为 int”的解决方案。这是最好的做法吗?

回答by Patrick Glandien

You may use C++11's std::round().

您可以使用 C++11 的std::round().

If you are still stuck with older standards, you may use std::floor(), which always rounds to the lower number, and std::ceil(), which always rounds to the higher number.

如果您仍然坚持使用旧标准,您可以使用std::floor(),它总是四舍五入到较低的数字,而std::ceil(),它总是四舍五入到较高的数字。

To get the normal rounding behaviour, you would indeed use floor(i + 0.5).

要获得正常的舍入行为,您确实会使用floor(i + 0.5).

This way will give you problems with negative numbers, a workaround for that problem is by using ceil() for negative numbers:

这种方式会给您带来负数问题,该问题的解决方法是对负数使用 ceil() :

double round(double number)
{
    return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}

Another, cleaner, but more resource-intensive, way is to make use of a stringstream and the input-/output-manipulators:

另一种更简洁但更占用资源的方法是使用字符串流和输入/输出操作符:

#include <iostream>
#include <sstream>

double round(double val, int precision)
{
    std::stringstream s;
    s << std::setprecision(precision) << std::setiosflags(std::ios_base::fixed) << val;
    s >> val;
    return val;
}

Only use the second approach if you are not low on resources and/or need to have control over the precision.

如果您不缺乏资源和/或需要控制精度,请仅使用第二种方法。

回答by Bill the Lizard

Using floor(num + 0.5)won't work for negative numbers. In that case you need to use ceil(num - 0.5).

使用floor(num + 0.5)不适用于负数。在这种情况下,您需要使用ceil(num - 0.5).

double roundToNearest(double num) {
    return (num > 0.0) ? floor(num + 0.5) : ceil(num - 0.5);
}

回答by Sani Singh Huttunen

There actually isn't a round function in Microsoft math.h.
However you could use the static method Math::Round() instead.
(Depending on your project type.)

Microsoft math.h 中实际上没有舍入函数。
但是,您可以改用静态方法 Math::Round()。
(取决于您的项目类型。)

回答by Elroy

I don't know if it's best practice or not but using the 0.5 technique with a floor() seems to be the way to go.

我不知道这是否是最佳实践,但使用 0.5 技术和 floor() 似乎是要走的路。