python - 如何将任何数字四舍五入到最接近的 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)会给我错误的输出。如何修复我的代码以获得正确的输出?
解决方案
你需要总是四舍五入:
import math
round_off = base * math.ceil(number / base)
推荐阅读
- google-cloud-storage - React-360 图像 URI 不可见
- coq - 在 Show Proof 上了解 COQ 证明。
- c# - 使用 MVVM Light 时如何将弹出窗口绑定到 ViewModel - BindingExpression 路径错误
- data-structures - Nasm 使用本地标签作为偏移量
- sonarqube - Sonarqube 拉取请求与多个构建的集成
- spring-data-mongodb - Spring Data MongoDB @Transactional 失败
- c# - 如何调试 Microsoft.Azure.Mobile.Server.Tables 包?
- excel - 如何忽略先前行中已计入累积计数的值
- android - 在 Activity 中使用单个 SearchView,用于不同的片段
- netty - 有没有办法动态调整 Netty 连接池的大小