2011-02-11 59 views
2

我不知道如何把x(從下面的代碼),並添加到自己得到的總和,然後除以評級數。在課堂上給出的例子是4個等級,數字是3,4,1和2.平均等級應該是2.5,但我似乎無法做到!如何獲得Python中範圍函數中所有數字的總和?

number_of_ratings = eval(input("Enter the number of difficulty ratings as a positive integer: "))  # Get number of difficulty ratings 
for i in range(number_of_ratings):  # For each diffuculty rating 
    x = eval(input("Enter the difficulty rating as a positive integer: "))  # Get next difficulty rating 
average = x/number_of_ratings 
print("The average diffuculty rating is: ", average) 
+1

你可以用數學這個問題。 `n *(n + 1)/ 2 =和(範圍(n + 1))`。這對n的大數值很有用。 – razpeitia 2011-02-11 06:18:54

+0

@raz:計算平均值時,你需要使用這個公式嗎? – Philipp 2011-02-11 14:32:27

回答

3

您的代碼不會添加任何內容,它只是在每次迭代中覆蓋x。可以使用+=運算符完成向變量添加內容。另外,不要使用eval

number_of_ratings = int(input("Enter the number of difficulty ratings as a positive integer: ")) 
x = 0 
for i in range(number_of_ratings): 
    x += int(input("Enter the difficulty rating as a positive integer: ")) 
average = x/number_of_ratings 
print("The average diffuculty rating is: ", average) 
1
try: 
    inp = raw_input 
except NameError: 
    inp = input 

_sum = 0.0 
_num = 0 
while True: 
    val = float(inp("Enter difficulty rating (-1 to exit): ")) 
    if val==-1.0: 
     break 
    else: 
     _sum += val 
     _num += 1 

if _num: 
    print "The average is {0:0.3f}".format(_sum/_num) 
else: 
    print "No values, no average possible!"