我對Python相當陌生,遇到了一個試圖計算一堆隨機數的平均值的障礙。該程序的總體概述是它是一個模具滾動程序它會提示用戶輸入一定數量的邊,然後滾動,直到程序輸出蛇眼。它也跟蹤雙打的數量和獲得蛇眼需要多長時間。然後創建整個程序中每個骰子的平均數量。這是我迷失的地方。計算多個隨機數的平均值Python
編輯:我刪除了我的原代碼,並在瓦西利斯的回答工作:
import random
while True:
#prompts user for valid number
user_s = int (input ("How many sides on your dice? "))
if user_s < 3:
print("That is not a valid size value, please enter a positive number")
if user_s >= 3:
break
print()
print("Thanks! Here we go...")
print()
double_count = 0
roll_count = 0
sum1 = 0 # Used to calculate sum of die_1
sum2 = 0 # Used to calculate sum of die_2
while True:
roll_count += 1
die_1 = random.randint(1,user_s)
die_2 = random.randint (1,user_s)
print(roll_count,".", " Die number 1 is ", die_1 , " and die number 2 is ", die_2, ".", sep ="")
if die_1 == die_2:
double_count += 1
if die_1 == 1 and die_2 == 1:
break
# Making sum
sum1 = sum1 + die_1
sum2 = sum2 + die_2
print("You finally got snake eyes on try number", roll_count)
print("Along the way you rolled a double", double_count,"times")
print(die_1)
print(die_2)
# Integer divisions
avg_roll1 = sum1 // roll_count
avg_roll2 = sum2 // roll_count
print("The average roll for die 1 was", format(avg_roll1,".2f"))
print("The average roll for die 2 was", avg_roll2)
但是像他指出,它並不需要全部通過所有的卷記錄的數字,而不是最後的數字。 任何幫助來實現這一點,將不勝感激。
謝謝!
有幾件事:一個'list'永遠不會等於一個整數。 'die_1 = [random.randint(1,user_s)]'不附加到列表,它只是替換它。如果你想保留原來的值(你已經正確地知道了你的值),你需要添加到列表中,而不是替換它。最後,由於'die_1'已經是一個列表,'[die_1]'是列表*的列表,所以'sum'不會真正起作用。 –