Python大整数比较不正确

0 投票
2 回答
777 浏览
提问于 2025-04-19 23:21

我刚开始学习一点Python,不知道为什么我写的脚本会返回一个数字,比如10000000000000000小于5。我猜这可能是因为在处理大数值时,int类型的精度问题,但我不太确定,也许我只是做错了什么!

这是我写得不太好的脚本:

def checkValue(n):
    while True:
        if n == '':
            print 'You didn\'t enter anything!'
            return False
        else:
            try:
                n = int(n)
            except ValueError:
                print 'That is not an integer!'
                return False
            else:
                break

    return True

while True:
    firstNum = raw_input('Enter the first number: ')
    if checkValue(firstNum) == False:
        continue
    else:
        break
while True:
    secNum = raw_input('Enter the second number: ')
    if checkValue(secNum) == False:
        continue
    else:
        break
while True:
    thirdNum = raw_input('Enter the third number: ')
    if checkValue(thirdNum) == False:
        continue
    else:
        break

if thirdNum > secNum and thirdNum > firstNum:
    print 'The third number is the biggest.'
elif secNum > firstNum:
    print 'The second number is the biggest.'
else:
    print 'The first number is the biggest.'

2 个回答

1

你需要把你的原始输入,比如说 firstNum 之类的,转换成一个整数。可以用 intfirstNum = int(firstNum) 这个方法来实现。

2

在你的 "checkValue" 函数里,你把输入的值转换成了 "int" 类型。但是在比较的时候,你却使用了输入的字符串值。所以你可以在输入阶段就把 "firstNum"、"secNum" 和 "thirdNum" 转换成数字。看看这个区别。

In [2]: firstNum = raw_input('Enter the first number: ')

In [3]: firstNum
Out[3]: '5'

In [4]: int_first = int(firstNum)

In [5]: int_first
Out[5]: 5

撰写回答