How to calculate average of int64_t [duplicate]

我的梦境 提交于 2019-12-24 10:03:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!