-3
「」「」計算在一個文件中輸入查詢值的平均值,代碼產生錯誤的輸出
num = 3
try: #set an exception in case of a file Error
while num >=0: '''read in values and place them in a file'''
value = int(input("Enter values: "))
my_file = open('my_data.txt', 'w+')
my_file.write(str(value))
numbers = my_file.readlines()
num -=1
my_file.close()
except IOError:
print('FILE FAILURE')
'''iterate to find the sum of the values in a file'''
total = 0
for ln in numbers:
total += int(ln)
'''Calculate the average'''
avg = total/len(numbers)
print("The average is %d"%(avg))#FIXME: does not calculate average
「代碼產生錯誤的輸出」究竟如何?您應該提供示例輸入和輸出。請注意,您將在每個將其截斷的迭代中打開該文件。你爲什麼寫信給該文件並立即讀取它? – DeepSpace
@DeepSpace,如果我輸入值,例如:2,4,7,5。輸出總是第三個數字。在這個例子中7.謝謝! – Umubale
請參閱我的評論的其餘部分。 – DeepSpace