c++将数字远离零舍入
您好,我想在 C++ 中像这样舍入双数(远离零):
4.2 ----> 5
5.7 ----> 6
-7.8 ----> -8
-34.2 ----> -35
执行此操作的有效方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如 Huppie 引用的文章中提到的,这最好表达为一个跨平台工作的模板所有浮点类型
请参阅 http://en.cppreference.com/w/cpp/numeric /math/floor 和 http://en.cppreference.com/ w/cpp/numeric/math/floor
或者,感谢 Pax,一个非函数版本:
As mentioned in the article Huppie cites, this is best expressed as a template that works across all float types
See http://en.cppreference.com/w/cpp/numeric/math/floor and http://en.cppreference.com/w/cpp/numeric/math/floor
or, thanks to Pax, a non-function version:
CPlusPlus.com 上有一篇关于类似问题的好文章。解决您的问题的简单方法应该是这样的:
更好的解决方案是文章中提到的,它使用模板:
There is a nice article about a similar problem on CPlusPlus.com. The easy solution to your problem should be something like this:
A better solution is the one mentioned in the article, which uses a template:
x < 0 ? Floor(x) : ceil(x);
Ruben Bartelink 的方法很好。但请考虑一下x = -0.0
、x = NaN
的特殊情况会发生什么。而不是让
myround(-0.0)
可能返回+0.0
1 并让myround(NaN)
返回一个更改了NaN
的有效负载,请考虑以下内容。myround_alt(-0.0)
返回-0.0
。myround_alt(NaN)
更有可能返回未更改的负载 NaN。非数字的东西很棘手并且没有很好的定义。 IAC,它是myround_alt(-0.0)
-->-0.0
我正在寻找。1IEC 60559 浮点算术 指定
ceil( ±0)
返回±0
,因此严格遵循该规范的实现不需要此方法。然而,许多 C 浮点实现并不遵循这一点(C 不需要它),或者在像这样的极端情况下失败。The
x < 0 ? floor(x) : ceil(x);
approach of Ruben Bartelink is good. Yet consider what happens with special cases ofx = -0.0
,x = NaN
.Rather than have
myround(-0.0)
potentially return+0.0
1 and havemyround(NaN)
return with a changed payload of theNaN
, consider the below.myround_alt(-0.0)
returns-0.0
.myround_alt(NaN)
more likely returns an unchanged payload NaN. Not-a-number stuff is tricky and not well defined. IAC, it is themyround_alt(-0.0)
-->-0.0
I am seeking.1IEC 60559 floating-point arithmetic specifies
ceil(±0)
returns±0
so this approach not needed with implementations that strictly follow that spec. Yet many C floating point implementation do not follow that (C does not require it) or fail in such comer cases like this.尝试
try