首先,你的函數只正在運行的10倍。您需要存儲您生成的值,而不是將它們打印到屏幕上。您可以通過將其存儲在列表中來完成此操作。
要獲得100個隨機變量的列表,你可以做[random.uniform(num1, num2) for i in range(100)]
。
然後,你需要找到這個的平均值。要獲得總金額,您可以做sum(list)
。要獲取值的數量,請執行len(list)
。如果我們結合這一切一起,我們得到:
import random
num1 = int(input("Input First number: "))
num2 = int(input("Input Second number: "))
random_numbers = [random.uniform(num1, num2) for i in range(100)]
print(sum(random_numbers)/len(random_numbers))
輸出是:
>>> import random
>>> num1 = int(input("Input First number: "))
Input First number: 10
>>> num2 = int(input("Input Second number: "))
Input Second number: 20
>>> random_numbers = [random.uniform(num1, num2) for i in range(10)]
>>> random_numbers
[13.083389212287019, 12.551686149990369, 13.881302022239865, 12.5156539109837, 12.340949073439575, 13.693758114264867, 13.972147752101735, 14.111313446849902, 11.693700678679372, 18.136716333128035]
>>> print(sum(random_numbers)/len(random_numbers))
13.5980616694
你有沒有考慮節省數以某種方式,而不是隻打印呢? – TigerhawkT3