2016-11-01 46 views
-5

我做了這個代碼,我希望它告訴我,它使用多少次發現我放在號碼,我想告訴它應該有多少次repite找到「stop_at」如何計算python中條件語句的輸出?

print 'first write the random int (lowest number first)' 

imp1 = float(raw_input()) 
imp2 = float(raw_input()) 
print 'the prosess will be between', imp1, 'and', imp2, 'when do you want to stop the opperation' 
stop_at = float(raw_input()) 


while True: 
    num = random.randint(imp1, imp2) 
    if num == stop_at: 
     print 
     print 
     print stop_at, "were found after", ..., 'tryes' 
     print '     ' 
     break 
    print num 
的作用

回答

0

首先,您不能使用float值作爲random.randint函數的輸入參數。輸入參數必須是integer。其次,stop_at也是如此。它必須是integer,因爲random.randint將返回integer(它可能是float,但只有它的形式爲2.011.0 ...)。第三,您應該引入計數器並將其增加到if部分代碼中以獲取命中數。此外,你應該介紹櫃檯,將被放置在while循環內,這將告訴你有多少循環。

1

您可以添加計數器

imp1 = int(raw_input("Enter low guess")) 
imp2 = int(raw_input("Enter high guess")) 
stop_at = int(raw_input("Enter the number you want guessed")) 

i = 0 
while True: 
    i += 1 
    num = random.randint(imp1, imp2) 
    if num == stop_at: 
     print "\n\n{0} was found after {1} tries\n\n".format(stop_at, i) 
    print num 
0

介紹一些計數變量,你將與每個迴路通遞增。

cnt = 0 
while True: 
    num = random.randint(imp1, imp2) 
    cnt += 1 
    if num == stop_at: 
     print 
     print 
     print stop_at, "were found after tryes {}".format(cnt) 
     print 
     break 
    print num 
+1

op詢問在stop_at之前重複動作的次數。找到at_stop時循環會中斷,匹配stop_at匹配的次數總是返回1 – SuperRafek