Python程序添加错误

时间:2014-03-08 03:06:21

标签: python

print ("This is a puzzle favored by Einstein. You will be asked to enter a three digit number, where the hundred's digit differs from the one's digit by at least two. The procedure will always yield 1089")
num = input("Give me a number which satisfies the rule of the game: ")
revnum = ((num[2]) + (num[1]) + (num[0]))
print("For the number: "+num+" the reverse number is: "+ revnum)
if num > revnum:
    print("The difference between ", num, "and ", revnum, "is ", int(num)-int(revnum))
else:
    print("The difference between ",revnum+" and ",num+" is ",int(revnum)-int(num))
if revnum > num:
    diff = str(float(revnum)-float(num))
else:
    diff = str(float(num)-float(revnum))
revdiff = (diff[2]+ diff[1]+diff[0])
print ("The reverse difference is: "+revdiff)
print ("The sum of: ",diff," and reversed difference is ",(diff + revdiff))

大家好,当我运行这个程序时,最后一行应该给我1089,无论用户输入什么,但我得到一个奇怪的号码...任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您将数字diffrevdiff转换为字符串,这使得diff + revdiff字符串连接。您需要将它们转换回最后一行中的数字才能使+正确。变化:

diff + revdiff

为:

int(diff)+int(revdiff)

float(revnum)之类的代码需要int(revnum),因为在将字符串转换为int时,例如int(diff)diff不应该是表示浮点数的字符串,例如"1.0"