Python 四舍五入到最接近的 0.25

Python round to nearest 0.25

我想将整数四舍五入到最接近的十进制值 0.25,如下所示:

import math

def x_round(x):
    print math.round(x*4)/4

x_round(11.20) ## == 11.25
x_round(11.12) ## == 11.00
x_round(11.37) ## == 11.50

这让我在 Python 中出现以下错误:

Invalid syntax

函数math.round不存在,只需使用内置round

def x_round(x):
    print(round(x*4)/4)

注意print是Python3中的一个函数,所以括号是必须的。

目前,您的函数 return 没有任何作用。 return 函数中的值可能比打印它更好。

def x_round(x):
    return round(x*4)/4

print(x_round(11.20))

如果要向上取整,使用math.ceil

def x_round(x):
    return math.ceil(x*4)/4

roundbuilt-in function in Python 3.4, and print 语法的改变。这在 Python 3.4:

中工作正常
def x_round(x):
    print(round(x*4)/4)

x_round(11.20) == 11.25
x_round(11.12) == 11.00
x_round(11.37) == 11.50