如何向上/向下舍入浮点值的小数位?C++ [英] How do I round up/down a decimal place of a float value? C++
问题描述
我知道您可以使用 setprecision(x) 来限制 cout 方法中显示的小数位数.我想知道如何向上/向下舍入一个小数位?
I know that you can use setprecision(x) to limit the amount of decimals displayed in the cout method. I was wondering how do I round a single decimal place up/down?
例如:我有数字:0.073
For example: I have the number: 0.073
我想把 7 向上舍入,即使 7 后面的数字是 3.所以数字变成:0.08
I want to round 7 upwards even though the number after 7 is 3. So the number becomes: 0.08
我曾尝试使用 ceil 和 floor,但这只能将其四舍五入为整数.我也有 ceilf,它也四舍五入为整数.
I have tried using ceil and floor, but that only rounds it to a whole number. I have ceilf as well, and that rounds to a whole number too.
推荐答案
两种可能如果你总是有那个数量级的数字,
Two possibilities if you always have numbers of that order of magnitude,
- 要么在四舍五入前加 0.005
- 或乘以 100,使用 ceil,然后除以 100.
如果您有不同数量级的数字,请使用 log10 找到数量级,然后通过上述方法之一进行四舍五入.
If you have numbers of different orders of magnitute, use log10 to find the order of magnitude and then do your rounding by one of the methods above.
这篇关于如何向上/向下舍入浮点值的小数位?C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!