The other answers address the problem with your code, however a better solution is to use a different algorithm.
I would use exponential smoothing (which is simpler to code, requires less data and produces a similar result). This is the technique I used to use when responsible for producing statistical performance reports. If readings are plotted this results in a smoother graph, which shows trends and discounts noise.
Briefly take the current sample, multiply by a discounting factor and add the a proportion of the current value.
s = x * α + (1-α) * s
To produce results from the start initialise the sample to the first reading then calculate.
See https://en.wikipedia.org/wiki/Exponential_smoothing
I would probably start with a smoothing factor of 0.73 - choose a largersmaller value to give more weight to past values.