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

Jas*_*yon 38 c++ rounding

重复:在C++中浮动的round()


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

我在google上看到一堆"添加0.5并转换为int"解决方案.这是最好的做法吗?

Pat*_*ien 63

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

如果你仍然坚持使用较旧的标准,你可以使用std::floor(),它总是舍入到较低的数字,并且std::ceil()总是向更高的数字舍入.

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

这种方式会给你带负数的问题,这个问题的解决方法是使用ceil()作为负数:

double round(double number)
{
    return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}
Run Code Online (Sandbox Code Playgroud)

另一种更清洁,但资源更密集的方法是使用字符串流和输入/输出操纵器:

#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;
}
Run Code Online (Sandbox Code Playgroud)

如果您的资源不足和/或需要控制精度,则仅使用第二种方法.

  • 您认为转换为字符串并返回更清洁*吗? (43认同)
  • 还需要包括<iomanip>(使用MSVC 2012)来使用round函数. (3认同)

Bil*_*ard 15

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

double roundToNearest(double num) {
    return (num > 0.0) ? floor(num + 0.5) : ceil(num - 0.5);
}
Run Code Online (Sandbox Code Playgroud)