问题
I need to calculate the average of n numbers. N is unknown at compile time. Each of the numbers could be an int64_t type but I know that also average fits in int64_t type. Problem is that the sum of n numbers could be too large for int64_t. Any suggestions?
回答1:
Average of two nos without overflow
Average = (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2)
This can be extended to n numbers as well.
Suppose you have n numbers from N1, N2....Nn-1, Nn
Average = (N1 / n) + (N2 / n) +.....+ (Nn-1 / n) + (Nn / n)
+
((N1 % n) + (N2 % n) +.....+ (Nn-1 % n) + (Nn % n)) / n
来源:https://stackoverflow.com/questions/56663116/how-to-calculate-average-of-int64-t