問題:基於用戶輸入計算兩個整數,其中第一個重複加倍,第二個除以二。在每個步驟中,如果第二個數字是奇數,則將第一個數字的當前值添加到其自身,直到第二個數字爲零。如何停止無限循環?
我的代碼似乎並沒有完全運行,我得到一個無限循環我做錯了什麼?我使用python 2.7.3
##
## ALGORITHM:
## 1. Get two whole numbers from user (numA and numB).
## 2. If user enters negative number for numB convert to positive.
## 3. Print numA and numB.
## 4. Check if numB is odd if True add numA to numA.& divide numB by 2 using int division.
## Print statement showing new numA and numB values.
## 5. Repeat steps 3 and 4 until numB is 0 or negative value. enter code here
## 6. Prompt user to restart or terminate? y = restart n = terminate
##
## ERROR HANDLING:
## None
##
## OTHER COMMENTS:
## None
##################################################################
done = False
while not done:
numA = input("Enter first integer: ") # 1. Get two whole numbers from user (A and B)
numB = input("Enter second integer: ") # 1. Get two whole numbers from user (A and B)
if numB < 0:
abs(numB) # 2. If user enters negative number for B convert to positive
print'A = ',+ numA,' ','B = ',+ numB
def isodd(numB):
return numB & 1 and True or False
while numB & 1 == True:
print'B is odd, add',+numA,'to product to get',+numA,\
'A = ',+ numA,' ','B = ',+numB,\
'A = ',+ numA+numA,' ','B = ',+ numB//2
else:
print'result is positive',\
'Final product: ', +numA
input = raw_input("Would you like to Start over? Y/N : ")
if input == "N":
done = True
不幸的是,您的代碼存在一堆問題。最大的一點是你永遠不會改變循環內的'numB',所以你一定會期望它循環無限! – katrielalex