舍入双打-.5-sprintf [英] Rounding doubles - .5 - sprintf

查看:56
本文介绍了舍入双打-.5-sprintf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码将其四舍五入为2dp:

I'm using the following code for rounding to 2dp:

sprintf(temp,"%.2f",coef[i]); //coef[i] returns a double

它成功地将6.666舍入到6.67,但是在舍入时不能正常工作5.555.它返回5.55,而应该(至少在我看来)返回5.56.

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.

如何在下一位数字为5时将其四舍五入?即返回5.56.

How can I get it to round up when the next digit is 5? i.e. return 5.56.

edit:我现在意识到这是在发生,因为当我使用cin输入5.555时,保存为5.554999997.

edit: I now realise that this is happening because when I enter 5.555 with cin it gets saved as 5.554999997.

我将尝试分两个阶段进行四舍五入-首先是3dp,然后是2dp.任何其他(更优雅)的想法?

I'm going to try rounding in two stages- first to 3dp and then to 2dp. any other (more elegant) ideas?

推荐答案

似乎您必须使用数学取整函数才能正确取整.

It seems you have to use math round function for correct rounding.

printf("%.2f %.2f\n", 5.555, round(5.555 * 100.)/100.);

这将在我的机器上提供以下输出:

This gives the following output on my machine:

5.55 5.56

这篇关于舍入双打-.5-sprintf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆