Python - 四分之一区间取整

21 投票
4 回答
11204 浏览
提问于 2025-04-17 06:16

我遇到了以下问题:

有一些数字,比如:

10.38

11.12

5.24

9.76

有没有现成的函数可以把它们四舍五入到最接近的0.25,比如:

10.38 --> 10.50

11.12 --> 11.00

5.24 --> 5.25

9.76 --> 9.75 ?

或者我可以自己动手写一个函数来完成这个任务吗?

提前谢谢你,

祝好

4 个回答

4

虽然没有现成的功能,但写这样一个函数其实很简单。

def roundQuarter(x):
    return round(x * 4) / 4.0
38

这是一个通用的解决方案,可以让你按照任意的精度进行四舍五入。对于你的具体情况,你只需要提供 0.25 作为精度,但也可以使用其他值,测试案例中有展示。

def roundPartial (value, resolution):
    return round (value / resolution) * resolution

print "Rounding to quarters"
print roundPartial (10.38, 0.25)
print roundPartial (11.12, 0.25)
print roundPartial (5.24, 0.25)
print roundPartial (9.76, 0.25)

print "Rounding to tenths"
print roundPartial (9.74, 0.1)
print roundPartial (9.75, 0.1)
print roundPartial (9.76, 0.1)

print "Rounding to hundreds"
print roundPartial (987654321, 100)

这将输出:

Rounding to quarters
10.5
11.0
5.25
9.75
Rounding to tenths
9.7
9.8
9.8
Rounding to hundreds
987654300.0
32

在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在程序中使用这些数据。这个过程就像是从冰箱里拿食材,然后用这些食材做饭一样。

首先,我们需要明确数据的来源,比如是从数据库、文件还是网络上获取。就像你决定从超市还是农贸市场买菜一样。

接下来,我们要把获取到的数据存储到一个地方,这样我们才能在需要的时候方便地使用它。就像把买回来的菜放进冰箱,随时可以拿出来做饭。

最后,当我们处理完这些数据后,可能还需要把结果展示出来,或者保存到某个地方。就像做完饭后,把菜端上桌,或者把剩下的菜放进冰箱一样。

总之,处理数据的过程就像做饭一样,需要准备、存储和展示,确保每一步都能顺利进行。

>>> def my_round(x):
...  return round(x*4)/4
... 
>>> 
>>> assert my_round(10.38) == 10.50
>>> assert my_round(11.12) == 11.00
>>> assert my_round(5.24) == 5.25
>>> assert my_round(9.76) == 9.75
>>> 

撰写回答