[英]Changing while loop to for loop
我想知道是否可以使用for loop
而不是while
來制作相同的代碼
d = 0.6
b = 0.0
h = 0.0
t = 0.0
count = 0
h = float(input("enter height: "))
b = float(input("enter a number of bounces: "))
t = h
while count < b:
if count == b - 1:
t += h * d
#print(t)
else:
h = h * d
t += h * 2
#print(t)
count += 1
#print (t)
print(t)
就像GLHF提醒我的那樣, b
應該是一個整數,以便下面的代碼起作用。
我沒有理由將變量b
表示為浮點數的反彈次數。 此外,在您的原始代碼中,您可以對count
(一個int)和b
(來自用戶輸入的浮動)進行比較。 如果b不是小數部分為0
的浮點數,則檢查將失敗,因此您可能需要將行更改為b = int(input('Enter the number of bounces))
for count in range(b-1): # generates a sequence from 0 to b-2
h *= d
t += h * 2
#print(t)
t += h * d
print(t)
由於您沒有將變量從float
類型更改為integer
,因此您無法執行此操作,因為您需要range()
函數,而range()
僅接受整數類型。
如果將變量設置為整數而不是浮點數,則可以在for循環中使用它;例如:
d = 0.6
b = 6 #bounce
h = 5 #height
t = 0.0
count = 0
t = h
for x in range(b):
if count == b-1:
t += h*d
else:
h *= d
t += h*2
count += 1
print (t)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.