我知道很多语言能够舍入到一定数量的小数位,例如使用Python:
>>> print round (123.123, 1)
123.1
>>> print round (123.123, -1)
120.0
但是我们如何围绕不十进制倍数的任意分辨率。例如,如果我想将数字四舍五入到最接近的一半或三分之一,那么:
123.123 rounded to nearest half is 123.0.
456.456 rounded to nearest half is 456.5.
789.789 rounded to nearest half is 790.0.
123.123 rounded to nearest third is 123.0.
456.456 rounded to nearest third is 456.333333333.
789.789 rounded to nearest third is 789.666666667.
答案 0 :(得分:7)
您可以通过简单地缩放数字来舍入到任意分辨率,即将数字乘以1除以分辨率(或者更容易,只需除以分辨率)。
然后将其四舍五入到最接近的整数,然后再缩放它。
在Python(这也是一种非常好的伪代码语言)中,它将是:
def roundPartial (value, resolution):
return round (value / resolution) * resolution
print "Rounding to halves"
print roundPartial (123.123, 0.5)
print roundPartial (456.456, 0.5)
print roundPartial (789.789, 0.5)
print "Rounding to thirds"
print roundPartial (123.123, 1.0/3)
print roundPartial (456.456, 1.0/3)
print roundPartial (789.789, 1.0/3)
print "Rounding to tens"
print roundPartial (123.123, 10)
print roundPartial (456.456, 10)
print roundPartial (789.789, 10)
print "Rounding to hundreds"
print roundPartial (123.123, 100)
print roundPartial (456.456, 100)
print roundPartial (789.789, 100)
在上面的代码中,它是提供功能的roundPartial
函数,应该很容易将其转换为具有round
函数的任何过程语言。
其余部分,基本上是测试工具,输出:
Rounding to halves
123.0
456.5
790.0
Rounding to thirds
123.0
456.333333333
789.666666667
Rounding to tens
120.0
460.0
790.0
Rounding to hundreds
100.0
500.0
800.0