有没有办法知道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整除)


回首忆惘然
浏览 83回答 4
4回答

喵喵时光机

尝试直接四舍五入到 4:import mathh = 53.75rounded = math.round(h / 4) * 4if (rounded > h):  print("Rounded up by " + str(rounded - h))else:   print("Rounded down by " + str(h - rounded))

青春有我

如果给定小数点后的数字是:则使用 round()>=5 + 1 将被添加到最终值。<5 表示最终值将按原样返回到上述小数位。但是您可以使用math 包中的ceil或floor,它总是分别向上或向下舍入。import math>>> math.ceil(5.2)6>>> math.floor(5.9)5

繁星淼淼

假设您想知道 和 是否3.9被4.4四舍五入。你可以这样做:def is_rounded_down(val, ndigits=None):&nbsp; &nbsp; return round(val, ndigits) < val然后你可以简单地调用该函数来找出>>> is_rounded_down(3.9)False>>> is_rounded_down(4.4)True默认情况下round()不会提供该信息,因此您需要自行检查。

慕妹3242003

对于 Python 2.X 整数除法返回一个整数并且总是向下舍入。add@LM1756:~$ pythonPython 2.7.13 (default, Sep 26 2018, 18:42:22)>>> print 8/32>>> print type(5/2)<type 'int'>对于 Python 3.X 整数除法返回浮点数,因此没有舍入。add@LM1756:~$ python3Python 3.5.3 (default, Sep 27 2018, 17:25:39)>>> print(8/3)2.6666666666666665>>> type(8/3)<class 'float'>>>>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python