round()用于C ++中的float [英] round() for float in C++
问题描述
我需要一个简单的浮点舍入函数,因此:
double round
pre>
round(0.1)= 0
round(-0.1)= 0
round(-0.9)= -1
我可以在math.h中找到ceil()和floor() - 而不是round()。
它存在于另一个名称下的标准C ++库中,或者它缺少了
解决方案)在C ++ 98标准库中。你可以自己写一个:
双轮(双d)
{
返回楼层+ 0.5);
}
在C ++ 98标准库中没有循环函数的可能原因它实际上可以以不同的方式实现。以上是一种常见的方式,但还有其他一些,例如 round-to-even ,这种方式较少有偏见,一般更好如果你要做很多舍入;但实现起来有点复杂。
I need a simple floating point rounding function, thus:
double round(double); round(0.1) = 0 round(-0.1) = 0 round(-0.9) = -1
I can find ceil() and floor() in the math.h - but not round().
Is it present in the standard C++ library under another name, or is it missing??
解决方案There's no round() in the C++98 standard library. You can write one yourself though:
double round(double d) { return floor(d + 0.5); }
The probable reason there is no round function in the C++98 standard library is that it can in fact be implemented in different ways. The above is one common way but there are others such as round-to-even, which is less biased and generally better if you're going to do a lot of rounding; it's a bit more complex to implement though.
这篇关于round()用于C ++中的float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!