如何计算int64_t的平均值 [英] How to calculate average of int64_t

查看:112
本文介绍了如何计算int64_t的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算n个数字的平均值. N在编译时未知.每个数字都可以是int64_t类型,但我知道平均值也适合int64_t类型.问题是n个数字的总和对于int64_t可能太大. 有什么建议吗?

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?

推荐答案

两个无溢出平均值

  Average = (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2)

这也可以扩展为n个数字.

This can be extended to n numbers as well.

假设您有N1,N2 .... Nn-1,Nn中的n个数字

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

这篇关于如何计算int64_t的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆