我需要一个简单的浮点四舍五入函数,因此:
double round(double);
round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1我可以在math.h中找到ceil()和floor() --但round()找不到。
它是以另一个名称出现在标准C++库中,还是丢失了??
发布于 2012-06-19 21:23:09
根据http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf的说法,它可以从cmath中的C++11获得。
#include <cmath>
#include <iostream>
int main(int argc, char** argv) {
std::cout << "round(0.5):\t" << round(0.5) << std::endl;
std::cout << "round(-0.5):\t" << round(-0.5) << std::endl;
std::cout << "round(1.4):\t" << round(1.4) << std::endl;
std::cout << "round(-1.4):\t" << round(-1.4) << std::endl;
std::cout << "round(1.6):\t" << round(1.6) << std::endl;
std::cout << "round(-1.6):\t" << round(-1.6) << std::endl;
return 0;
}输出:
round(0.5): 1
round(-0.5): -1
round(1.4): 1
round(-1.4): -1
round(1.6): 2
round(-1.6): -2发布于 2009-01-28 06:10:29
在C++98标准库中没有round()。不过,你也可以自己写一个。下面是round-half-up的一个实现
double round(double d)
{
return floor(d + 0.5);
}在C++98标准库中没有round函数的可能原因是它实际上可以以不同的方式实现。上面是一种常见的方法,但也有其他方法,如round-to-even,它的偏差较小,如果您要进行大量舍入,通常会更好;尽管实现起来有点复杂。
发布于 2011-05-02 00:19:31
Boost提供了一组简单的舍入函数。
#include <boost/math/special_functions/round.hpp>
double a = boost::math::round(1.5); // Yields 2.0
int b = boost::math::iround(1.5); // Yields 2 as an integer有关详细信息,请参阅Boost documentation。
编辑:从C++11开始,就有了std::round, std::lround, and std::llround。
https://stackoverflow.com/questions/485525
复制相似问题