四舍五入双打 - .5 - sprintf
我使用以下代码舍入到 2dp:
sprintf(temp,"%.2f",coef[i]); //coef[i] returns a double
它成功地将 6.666 舍入到 6.67,但舍入时无法正常工作 5.555。 它返回 5.55,而它应该(至少在我看来)返回 5.56。
当下一个数字是 5 时如何使其四舍五入? 即返回5.56。
编辑:我现在意识到这种情况正在发生,因为当我用 cin 输入 5.555 时,它得到 另存为 5.554999997。
我将尝试分两个阶段进行舍入 - 首先到 3dp,然后到 2dp。 任何其他 (更优雅)想法?
I'm using the following code for rounding to 2dp:
sprintf(temp,"%.2f",coef[i]); //coef[i] returns a double
It successfully rounds 6.666 to 6.67, but it doesn't work properly when rounding
5.555. It returns 5.55, whereas it should (at least in my opinion) return 5.56.
How can I get it to round up when the next digit is 5? i.e. return 5.56.
edit: I now realise that this is happening because when I enter 5.555 with cin it gets
saved as 5.554999997.
I'm going to try rounding in two stages- first to 3dp and then to 2dp. any other
(more elegant) ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
看来您必须使用数学舍入函数才能正确舍入。
这在我的机器上给出了以下输出:
It seems you have to use math round function for correct rounding.
This gives the following output on my machine:
数字
5.555
无法表示为 IEEE754 中的精确数字。 用"%.50f"
打印常量5.555
结果是:所以它将向下舍入。 尝试使用它来代替:
尽管您需要小心可以精确表示的数字,因为它们会被这个表达式错误地舍入。
您需要了解浮点表示的局限性。 如果获得准确性很重要,则可以使用(或编码)BCD 或其他没有 IEEE754 表示法缺点的十进制类。
The number
5.555
cannot be represented as an exact number in IEEE754. Printing out the constant5.555
with"%.50f"
results in:so it will be rounded down. Try using this instead:
although you need to be careful of numbers that can be represented exactly, since they'll be rounded up wrongly by this expression.
You need to understand the limitations of floating point representations. If it's important that you get accuracy, you can use (or code) a BCD or other decimal class that doesn't have the shortcoming of IEEE754 representation.
另一种可能的解决方案怎么样:
这个想法是将数字远离零(n * 2得到正确的符号)增加浮点数学可表示的最小可能量。
例如:
对于 MSVC 产量:
How about this for another possible solution:
The idea is to increase the number away from zero (the n*2 gets the sign right) by the smallest possible amount representable by floating point math.
Eg:
With MSVC yields:
这个问题被标记为 C++,所以我将在这个假设下继续。 请注意,与 C printf 系列不同,C++ 流将进行舍入。 您所要做的就是提供您想要的精度,流库将为您舍入。 我只是把它扔在那里以防万一你还没有理由不使用流。
This question is tagged C++, so I'll proceed under that assumption. Note that the C++ streams will round, unlike the C printf family. All you have to do is provide the precision you want and the streams library will round for you. I'm just throwing that out there in case you don't already have a reason not to use streams.
您也可以这样做(保存乘法/除法):
You could also do this (saves multiply/divide):