Python程序挂起了某些数字

时间:2015-02-19 04:52:36

标签: python

我创建了一个程序,它将两个数字分开,然后以十进制形式返回答案。它适用于我测试的所有数字,除了8和9以及两者的任意组合。关于为什么会发生这种情况的任何解释都是受欢迎的。

cont = True
while(cont):
    initChoice = 0
    print " "
    print "What would you like to do?"
    print "1) Divide two numbers"
    print "2) Find the GCD of two numbers"
    print "3) Find the LCM of two numbers"
    print "0) Exit"
    initChoice = input("")
    if(initChoice == 1):
        #This hangs up when certain numbers are entered
        #It only seems to hang up when only 8 or 9 are involved
        #For example (8,9) (9,8) (88,89) (89,88) (98,99) (99,98)
        #It gets hung up on num1 = num1-num2
        num1 = raw_input("Please enter the first number: ")
        num2 = raw_input("Please enter the second number: ")
        num1 = float(num1)
        num2 = float(num2)
        numer = num1
        denom = num2
        ans = 0.0
        iter1 = 0.0
        iter2 = 0.0
        while(num1 > 0):
            if(num1 >= num2):
                num1 = num1-num2
                iter1 += 1
            else:
                num2 = num2*0.1
                ans += iter1*(10**(-iter2))
                iter1 = 0
                iter2 += 1      
        ans += iter1*(10**(-iter2))
        print numer,"divided by",denom,"is",and

是的,我知道它会无限期地运行,我有更多的代码可以结束循环。

2 个答案:

答案 0 :(得分:0)

更改while循环条件以检查num2是否为“while(num1> 0和num2> 0)”:“。这应该工作。

答案 1 :(得分:0)

" while(num1> 0)"绝对是个问题。它必须与计算机上浮点指针变量的精度有关。从python你可以找到它导入sys如下:

sys.float_info.min

因此,您的代码可能与下面的代码类似,以避免无限循环。

from sys import float_info

cont = True
while(cont):
    initChoice = 0
    print " "
    print "What would you like to do?"
    print "1) Divide two numbers"
    print "2) Find the GCD of two numbers"
    print "3) Find the LCM of two numbers"
    print "0) Exit"
    initChoice = input("")
    if(initChoice == 1):
        #This hangs up when certain numbers are entered
        #It only seems to hang up when only 8 or 9 are involved
        #For example (8,9) (9,8) (88,89) (89,88) (98,99) (99,98)
        #It gets hung up on num1 = num1-num2
        num1 = raw_input("Please enter the first number: ")
        num2 = raw_input("Please enter the second number: ")
        num1 = float(num1)
        num2 = float(num2)
        numer = num1
        denom = num2
        ans = 0.0
        iter1 = 0.0
        iter2 = 0.0

        precision=float_info.min

        while(num1 > 0+precision):
            if(num1 >= num2):
                num1 = num1-num2
                iter1 += 1
            else:
                num2 = num2*(0.1)
                ans += iter1*(10**(-iter2))
                iter1 = 0
                iter2 += 1
        ans += iter1*(10**(-iter2))
        print numer,"divided by",denom,"is",ans

    elif(initChoice == 0):
        break