Boo*_*d16 10 python floating-point rounding
我想将一个浮点数舍入到下一个偶数.
脚步:
1)检查数字是奇数还是偶数
2)如果是奇数,则向上舍入到下一个偶数
我已准备好第1步,这是一个检查给定号码是否均匀的函数:
def is_even(num):
if int(float(num) * 10) % 2 == 0:
return "True"
else:
return "False"
Run Code Online (Sandbox Code Playgroud)
但我正在努力迈出第2步......
有什么建议?
注意:所有花车都是正面的.
Mar*_*ers 26
不需要步骤1.只需将值除以2,向上舍入到最接近的整数,然后再乘以2:
import math
def round_up_to_even(f):
return math.ceil(f / 2.) * 2
Run Code Online (Sandbox Code Playgroud)
演示:
>>> import math
>>> def round_up_to_even(f):
... return math.ceil(f / 2.) * 2
...
>>> round_up_to_even(1.25)
2
>>> round_up_to_even(3)
4
>>> round_up_to_even(2.25)
4
Run Code Online (Sandbox Code Playgroud)