2017-04-07 556 views
3

我正在研究一個問題,它告訴我創建一個計算溫度的程序,這取決於錶盤上有多少「點擊」。溫度從40開始,並停止,90,一旦停止,它會回到40並重新開始。Python限制在一個範圍內

clicks_str = input("By how many clicks has the dial been turned?") 
clicks_str = int(clicks_str) 

x = 40 
x = int(x) 

for i in range(1): 
    if clicks_str > 50: 
     print("The temperature is",clicks_str -10) 
    elif clicks_str < 0: 
     print("The temperature is",clicks_str +90) 
    else: 
     print("The temperature is", x + clicks_str) 

當我把輸入1000次點擊,溫度自然去990,我可以看到,從代碼,但我怎麼會做這麼「溫度」是在40號90之間和

+3

什麼呢'因爲我在範圍(1):'你意味着什麼?我相信你可以很容易地從你的代碼中取出它。 – ozgur

回答

1

問題似乎與您使用範圍函數有關,因爲如果您不知道需要修改clicks_str直到您得到溫度在40和90之間的值。您還打印'溫度」每次修改clicks_str,但它可能不是正確的溫度,但(直到你得到clicks_str在0〜50)

一個更好的辦法來解決這個問題是使用while循環:

clicks_str = int(input("By how many clicks has the dial been turned?")) 
x = 40 

while True: 
    if clicks_str > 50: 
     clicks_str -= 50 
    elif clicks_str < 0: 
     clicks_str += 50 
    else: 
     print("The temperature is", x + clicks_str) 
     break # breaks while loop 

甚至更​​多的方式簡單地fedterzi在答覆中表示是通過使用模量:

clicks_str = int(input("By how many clicks has the dial been turned?")) 
x = 40 

temp = (clicks_str % 50) + x 
print("The temperature is {}".format(temp)) 
+0

所以while循環確保循環的數字是40-90? –

+0

在這種情況下,while循環會一直運行,直到遇到中斷爲止。正如你所看到的,一旦0

4

如果您將溫度表示爲介於0到50(90-40)之間的數字,則可以使用模數運算,然後加40以獲得原始溫度。

clicks_str = input("By how many clicks has the dial been turned?") 
clicks_str = int(clicks_str) 

temp = (clicks_str % 51) + 40 
print("The temperature is {}".format(temp)) 
1

你的代碼可能是這樣,你並不需要將數字轉換成int和你可以輸入在一行代碼INT:

clicks_str = int(input("By how many clicks has the dial been turned?")) 

x = 40 

if clicks_str > 50: 
    print("The temperature is",clicks_str -10) 
elif clicks_str < 0: 
    print("The temperature is",clicks_str +90) 
else: 
    print("The temperature is", x + clicks_str) 

當你進入clicks_str == 1000或大於50的任何值,則輸出爲:clicks_str -10