我是python的初学者。我编写了一个简单的程序来查找 3 个数字中的最大值。当我给出具有相同位数(例如 50 80 20)的输入数字时,我会得到正确的答案。但是,当我提供输入 (50 130 20) 时,它不起作用。
我究竟做错了什么?
num1=input("Enter 3 numbers\n")
num2=input()
num3=input()
if(num1 > num2):
if(num1 > num3):
print("The greatest number is "+ str(num1))
else:
print("the greatest number is "+ str(num3))
else:
if(num2 > num3):
print("The greatest number is " + str(num2))
else:
print("The greatest number is " + str(num3))
您是动态类型的另一个受害者。
当您将数据读入num
变量时,变量被视为字符串。
当 Python 使用<
or>
运算符比较两个字符串时,它是按字典顺序进行的——意思是按字母顺序。这里有几个例子。
'apple' < 'orange' //true
'apple' < 'adam' //false
'6' < '7' //true as expected
'80' < '700' //returns false, as 8 > 7 lexiographically
因此,您希望使用 转换您的输入int()
,以便<
比较按预期工作。
代码
num1=int("Enter 3 numbers\n")
num2=int(input())
num3=int(input())
if(num1 > num2):
if(num1 > num3):
print("The greatest number is "+ str(num1))
else:
print("the greatest number is "+ str(num3))
else:
if(num2 > num3):
print("The greatest number is " + str(num2))
else:
print("The greatest number is " + str(num3))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句