Python round to nearest 0.25 [duplicate]

发布于 2021-01-29 14:11:14

This question already has answers here :

Syntax error on print with Python 3
[duplicate]

(3 answers)

Closed 5 years ago.

I want to round integers to the nearest 0.25 decimal value, like this:

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

This gives me the following error in Python:

Invalid syntax
关注者
0
被浏览
125
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    The function math.rounddoes not exist, just use the built in round

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

    Note that print is a function in Python 3, so the parentheses are required.

    At the moment, your function doesn’t return anything. It might be better to
    return the value from your function, instead of printing it.

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

    If you want to round up, use math.ceil.

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看