2017-04-07 1489 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