首页 > 解决方案 > 如何将任何数字四舍五入到最接近的 5 的倍数?

问题描述

我一直在尝试将任何数字四舍五入到最接近的 5 的倍数。这么说,我的意思是它应该总是四舍五入。但是,我的一段代码总是根据我输入的数字向上或向下四舍五入到最接近的 5 的倍数。数字始终int整数。这是我的代码:

num = int(input())
base = 5
for x in range(num):
    number = int(input())
    round_off = base * round(number/base)
    print(round_off)

输入和输出:

in:4
in:73
out:75 #correct
in:67
out:65 #wrong, should be 70
in:38
out:40 #correct
in:33
out:35 #correct

如您所见,只有 67 和可能其他类似的(如 57)会给我错误的输出。如何修复我的代码以获得正确的输出?

标签: pythonpython-3.xalgorithm

解决方案


你需要总是四舍五入

import math
round_off = base * math.ceil(number / base)

推荐阅读