2016-04-18 24 views
0

我想要一個程序工作。我幾乎擁有它,但有些東西仍然會導致錯誤。Python中的百分數

主要思想是,程序會做這些事情:

  • 從免費用戶的%向投擲命中(1 - 100 INT)
  • 刺激與而1000投與每把它計算如果它擊中或未命中。
  • 關於每個投擲必須有一行:命中或未命中。
  • 總結所有擊中和最後打印它。

例子:

Insert % of free throws: 45 
1. throw hits 
2. throw hits 
3. throw misses 
4. throw hits 
... 
997. throw misses 
998. throw misses 
999. throw hits 
1000. throw misses 
Hits 458 throws. 

我創造了這個:

from random import randint 
percent = int(input("Insert % of free throws: ")) 
var = 1 
hits = 0 
while var < 1000: 
if randint(1, 100) <= percent: 
    var = var + 1 
    print(str(var) + '. throw hits') 
    hits = hits + var 
else: 
    print(str(var) + '. throw misses') 

print("Hits " + str(hits) + " throws.") 

但也有一些錯誤。首先,如果我插入0%,那麼它會變得瘋狂,第二個是,命中數是可笑的 - 比如500500等等。我有想法VAR!= 0但它仍然不工作,數數的事情仍然是我的神祕。我試圖在var之前和之後「點擊」,但它仍然不起作用。 任何人有想法讓我走上正軌?

+0

您需要縮進'while'的主體。 – Barmar

回答

1

問題是,你只有在得到命中時增加了var,你應該增加它的每一個投擲。所以只需使用簡單的for循環即可。

而且你應該每增加一次hits一次,而不是var

for var in range(1, 1001): 
    if randint(1, 100) <= percent: 
     hits += 1 
     print(str(var) + '. throw hits') 
    else: 
     print(str(var) + '. throw misses') 
print ("Hits " + str(hits) " throws.") 

注意range()不包括在範圍的結束數,因此要獲得1000罰球開始var = 1,你必須使用1001作爲結束。

1

Barmar認爲結果值中存在奇怪的原因,所以讓我選擇一些要點進行回顧,因爲這是一個說明性的代碼示例。

在Python做加權分佈的 「標準」 方法是:

random.random() < pct 

凡PCT爲1的一小部分,e.g 45% - > 0.45。這將更改您的代碼:

percent = int(input("Insert % of free throws: "))/100 

... 
    if random.random() < percent: 
     ... 

其他挑剔包括避免while環路只要有可能。你很少需要Python中的while循環,它不是while True。使用for循環,尤其是因爲您試圖跟蹤循環索引!再加上其他一些調整,你會得到...

hitcount = 0 

for i in range(1, 1001): # loop from 1 -> 1000 inclusive 
    if random.random() < percent: 
     hitcount += 1 
     msg = "{}. throw hits".format(i) 
    else: 
     msg = "{}. throw misses".format(i) 
    print(msg) 
print("Hit {} throws.".format(hitcount)) 

值得注意的是這款採用str.format而不是字符串建築與%運營商。這是首選。