如何解决如何在python中使用int()将数字四舍五入到其最小值
我想要的是:
if 1700 / 1000 = 1.7 = int(1) # I want this to be True
lst.append("T")
我的原始代码是:
if 1700 / 1000 == int(1) # This is False and I want it to be True
lst.append("T")
if 语句为 False,因为答案是 1.7 而不是 1。我希望这是真的。所以我希望使用 int 将 1.7 向下舍入为 1,以便 if 语句为 True。
解决方法
//
始终提供 int 值。如果您想始终获得 int
,请使用它,否则请遵循 int(a/b)
if 1700 // 1000 == int(1): # I want this to be True
lst.append("T")
,
你要么需要把 int 放在另一边:
if int(1700 / 1000) == 1
lst.append("T")
即在比较之前将 1700/1000 舍入为整数,
或使用 //
,这是整数除法并丢弃小数部分:
if 1700 // 1000 == 1
lst.append("T")
,
您可以使用 //
运算符(整数除法)或使用 floor
模块中的 math
函数:
>>> from math import floor
>>> floor(1.7/1)
1
>>> floor(1.7/1) == int(1)
True
>>> 1.7 // 1
1.0
>>> 1.7 // 1 == 1
True
,
你可以试试
if int(1700/1000) == 1 # I want this to be True
lst.append("T")
int(1700/1000) 将通过忽略数字的小数部分将 1.7 转换为 1
,一切精彩都很简单
if int(1700 / 1000) == int(1):
lst.append("T")
,
你应该看看 floor 和 ceil 函数。 floor 函数舍入到最后一个数字,而 ceil 舍入到下一个。在您的情况下,您需要这样做:
import math
if math.floor(1700 / 1000) == int(1):
print("TRUE")
else:
print("FALSE")
,
您可以在 Python 中通过 'math' 库中的 'floor' 和 'ceil' 方法进行四舍五入。
from math import floor,ceil
print (floor(1.7),',ceil(1.7))
结果是
1,2
这适用于 Python 2.x 或 Python 3.x
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。