+ 3
Can you calculate average by adding one number
This ia mathematical question but I like to do it in code. Values : 4,8,12 The first average of 4 and 8 is 6 If I have a new number say 12 Do I really need to calculate a new total and divide that by 3. Or is there a smart way, which result in a correct average ?
5 Respuestas
+ 6
If you only add one element and x denotes the new amount of elements, the new average would equal
( x - 1 / x ) * oldAverage + ( 1 / x ) * newElement
Not sure if that is better though. Maybe someone else can provide an even smarter method.
+ 4
If you use the formula that Shadow mentioned, make sure you use floating point division.
+ 2
Yes! You can write a while loop that takes input and appends it to the array, then print the array sum divided by the array length. Putting it inside a while loop would allow you to keep adding elements to the array.
+ 2
Shadow nailed it and I believe that's the straightforward way by reversing the computed average and I would like to add some explanation on top of it.
Basically what the formula does is:-
✔ Obtain the sum of original number list by multiplying original average with its size
✔ Add the new number in and finally divide by the new size
That's the reason we have both addend sharing the same denominator. 😉
0
I managed to implement it in code
And it does work.
Thank you.
https://code.sololearn.com/cbWtOagXA65L