python - 为真陈述而假

标签 python floating-point int

在下面的代码中,当a,b,c的输入分别为2,3和4时,

a=input('Enter length of first side of triangle: ')
b=input('Enter length of second side of triangle: ')
c=input('Enter length of third side of triangle: ')
print((a+b)>c)

输出是

False

但如果输入更改为 float (如下图所示),

a=float(input('Enter length of first side of triangle: '))
b=float(input('Enter length of second side of triangle: '))
c=float(input('Enter length of third side of triangle: '))
print((a+b)>c)

那么输出是

True

请解释为什么会这样

最佳答案

您的第一个片段的结果是:

('2' + '3') > '4'
# which is equivalent to:
'23' > '4'

在 python 中,字符串是根据它们的 unicode 值进行比较的,每次比较一个字符。于是上面的比较就变成了:

ord('2') > ord('4')
# which is equivalent to
50 > 52

这是False

另一方面,您的第二个片段是一个简单的float 比较:

(2.0 + 3.0) > 4.0

这是

关于python - 为真陈述而假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55037812/

相关文章:

c++ - 使用 double 时精度损失

math - float 学坏了吗?

c - 注意: expected 'float *' but argument is of type 'int *'

Python:PerformanceWarning:将对象数据类型数组添加/减去未矢量化的 TimedeltaArray

python - 多标签分类器中的拟合概率

Python 关于舍入的奇怪行为

java - 为什么 Java 能够将 0xff000000 存储为 int?

c# - Java 和 C# 中的 int 和 Integer 有什么区别?

python - 向所有客户端发送消息

Python:如何将信息从 .csv 文件导入到 python 作为一个包含元组的列表?