首页 > 解决方案 > 有没有办法知道在 python 中某些东西是向上还是向下取整?

问题描述

我基本上想知道我的方程的结果(这是一个像这样的简单方程x / y)是向上还是向下舍入。原因是我在舍入线之后有两个简单的语句,如下所示:

if h % 2 != 0: h = h + 1
if h % 4 != 0: h = h + 2

并且根据舍入的方向,我会选择+or-运算符,所以如果结果向上取整,h % 2 != 0那么它就是h = h + 1,如果它被向下取整,那么h = h - 1.

round()提供那种信息吗?

另外,我的数学正确吗?(我希望结果可以被 4 整除)

标签: pythonrounding

解决方案


试试这个直接四舍五入:

import math

h = 53.75
rounded = math.round(h / 4) * 4

if (rounded > h):
  print("Rounded up by " + str(rounded - h))
else:
   print("Rounded down by " + str(h - rounded))

推荐阅读