将双数四舍五入到十分位 [英] Rounding a double number up to the tenths place

查看:133
本文介绍了将双数四舍五入到十分位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在C ++中浮动的round()

好吧,假设我具有数字 8.47434 。我想将其四舍五入到8.5并保留小数点后一位。我将如何在C ++中做到这一点

Ok suppose I had the number 8.47434. I want to round it up to 8.5 and to 1 decimal place. How would I go about doing this in C++

推荐答案

乘以 10 ,取整并再次除以 10

Multiply by 10, round and divide by 10 again.

示例:

round(10 * 8.47434f) / 10;

编辑:

好的,我刚发现 round()并不总是出现在 math.h 中。

OK, I just found out that round() is not always present in math.h.

以上内容适用于gcc和icl(具有Microsoft的库),但不适用于tcc。

The above works in gcc and icl (with Microsoft's libraries), but not in tcc.

floor()是标准库的一部分。因此,我们可以添加 0.5 并使用 floor()

floor(), however, is part of the standard libraries. So to round, we can add 0.5 and use floor().

示例:

floor(10 * 8.47434f + 0.5f) / 10;

这篇关于将双数四舍五入到十分位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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