[英]Hailstone sequence using nested while loops
我正在編寫一個程序,該程序允許用戶輸入一定范圍的數字,然后該程序將對該范圍內的每個數字進行一次冰雹序列處理,然后將打印出最大循環長度的數字。 我看不到為什么我的代碼無法正常工作。 我們需要使用while循環
def main():
#set starting variables
start_num = int(input('Enter starting number of the range: '))
#check if the numbers entered are positive and that the start is less than the end
while (start_num < 1):
start_num = int(input('Enter a positive starting number of the range: '))
end_num = int(input('Enter ending number of the range: '))
while (end_num < 1):
end_num = int(input('Enter a positive ending number of the range: '))
while (start_num > end_num):
start_num = int(input('Enter starting number of the range: '))
end_num = int(input('Enter ending number of the range: '))
cycle_length = 0
max_length = 0
num_max = 0
num = 0
while (start_num < end_num):
while (num != 1):
if (start_num % 2 == 0):
num = start_num / 2
cycle_length = cycle_length +1
else:
num = (start_num * 3) + 1
cycle_length = cycle_length +1
if (cycle_length >= max_length):
max_length = cycle_length
num_max = start_num
cycle_length = 0
start_num = start_num + 1
print(num_max)
print(max_length)
main()
在while
循環中,您始終在檢查start_num
,它永遠不會改變。 在循環的最開始,您需要將num
設置為start_num
。 然后在整個循環體內使用num
。
我將仔細檢查每一行,並告訴您問題所在。 您應該真正確保知道每個變量持有什么以及應該持有什么。
def main():
#set starting variables
start_num = int(input('Enter starting number of the range: '))
#check if the numbers entered are positive and that the start is less than the end
while (start_num < 1):
start_num = int(input('Enter a positive starting number of the range: '))
end_num = int(input('Enter ending number of the range: '))
while (end_num < 1):
end_num = int(input('Enter a positive ending number of the range: '))
while (start_num > end_num):
start_num = int(input('Enter starting number of the range: '))
end_num = int(input('Enter ending number of the range: '))
cycle_length = 0
max_length = 0
num_max = 0
num = 0
while (start_num < end_num):
start_num
和end_num
不會改變,因此您有一個無限循環,例如while(10 <100)
while (num != 1):
num
當前為0,因為幾行前將其設置為0后尚未將其分配給任何內容
if (start_num % 2 == 0):
num = start_num / 2
num
現在是start_num/2
,但start_num
永不更改
cycle_length = cycle_length +1
else:
num = (start_num * 3) + 1
同樣在這里
cycle_length = cycle_length +1
if (cycle_length >= max_length):
max_length = cycle_length
num_max = start_num
您正在將num_max
設置為start_num
但是start_num
永不更改
cycle_length = 0
您正在每個周期重置cycle_num
start_num = start_num + 1
print(num_max)
print(max_length)
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.