+ 1
Help!! With Averaging Numbers From a Text file in python without using sum()
Hello! I am truly stuck on this question, I can get an *average* with what I have, however, my numbers are way off. The answer is 0.750718518519. But I keep getting 0.7507185185185187. What am I missing? count = 0 total = 0 ### obtaining the file###### fname = input("Enter file name: ") fh = open(fname) ### The loop #### for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue # Getting the average ##### count = count + 1 lane = line.find(':') fin = line[lane + 1: ] value = float(fin) total = total + value ## Final number##### if count : average = total / count print (average)
5 ответов
+ 3
Looks like "normal" floating point rounding errors to me. Look into the decimal module for more precision. And don't forget to close your input file 🤓
+ 2
Your calculator is just truncating the number earlier than python...
+ 1
Hello Jackson! Thank you for replying. Where do I stop it from doing that???
+ 1
Easiest would be:
print(round(average, x))
Where you replace x with the number of decimal places you want.
+ 1
Unfortunately no, I am still unable to get the answer: 0.750718518519
With that solution, I get the output: 0.8
Thank you for your help anyway :)