c + +舍入从零开始的数字 [英] c++ rounding of numbers away from zero
本文介绍了c + +舍入从零开始的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在C ++中四舍五入像这样的双数(远离零):
Hi i want to round double numbers like this (away from zero) in C++:
4.2 ----> 5
5.7 ----> 6
-7.8 ----> -8
-34.2 ----> -35
执行此操作的有效方法是什么?
What is the efficient way to do this?
推荐答案
inline double myround(double x)
{
return x < 0 ? floor(x) : ceil(x);
}
如文章Huppie引用,最好将其表示为适用于所有浮动类型的模板
As mentioned in the article Huppie cites, this is best expressed as a template that works across all float types
请参见 http://en.cppreference.com/w/cpp/数字/数学/地板和 http://en.cppreference。 com / w / cpp / numeric / math / floor
,或者,由于Pax,非功能版本:
or, thanks to Pax, a non-function version:
x = (x < 0) ? floor(x) : ceil(x);
这篇关于c + +舍入从零开始的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文