gpt4 book ai didi

python - 为真陈述而假

转载 作者:行者123 更新时间:2023-11-28 20:13:13 26 4
gpt4 key购买 nike

在下面的代码中,当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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com