3长整型平均整型、平均

2023-09-03 08:22:00 作者:那条不归路我会一直走下去

我有3个非常大的有符号整数。

I have 3 very large signed integers.

long x = long.MaxValue;
long y = long.MaxValue - 1;
long z = long.MaxValue - 2;

我想计算他们的平均截断。预计平均值为 long.MaxValue - 1 ,这是 9223372036854775806

这是不可能计算出它:

long avg = (x + y + z) / 3; // 3074457345618258600

注:我看过所有关于平均水平的2号这些问题,但我不明白怎么说技术可以应用的3个数字平均

Note: I read all those questions about average of 2 numbers, but I don't see how that technique can be applied to average of 3 numbers.

这将是很容易与的BigInteger 的用法,但让我们假设我不能使用它。

It would be very easy with the usage of BigInteger, but let's assume I cannot use it.

BigInteger bx = new BigInteger(x);
BigInteger by = new BigInteger(y);
BigInteger bz = new BigInteger(z);
BigInteger bavg = (bx + by + bz) / 3; // 9223372036854775806

如果我转换为,然后,当然,我输了precision:

If I convert to double, then, of course, I lose precision:

double dx = x;
double dy = y;
double dz = z;
double davg = (dx + dy + dz) / 3; // 9223372036854780000

如果我转换为十进制,它的工作原理,同时也让我们假设我不能使用它。

If I convert to decimal, it works, but also let's assume that I cannot use it.

decimal mx = x;
decimal my = y;
decimal mz = z;
decimal mavg = (mx + my + mz) / 3; // 9223372036854775806

问:有没有一种方法来计算3个非常大的整数截断平均只有与的使用很长键入?不考虑这个问题,因为C#特异性,只是更容易为我提供的样品在C#。

Question: Is there a way to calculate the truncated average of 3 very large integers only with the usage of long type? Don't consider that question as C#-specific, just it is easier for me to provide samples in C#.

推荐答案

这code将工作,但不是pretty的。

This code will work, but isn't that pretty.

它首先将所有三个值(这层楼的价值观,所以你输的余数),然后把其余的:

It first divides all three values (it floors the values, so you 'lose' the remainder), and then divides the remainder:

long n = x / 3
         + y / 3
         + z / 3
         + ( x % 3
             + y % 3
             + z % 3
           ) / 3

请注意,上述示例不总是具有一个或多个负值时正常工作。

Note that the above sample does not always work properly when having one or more negative values.

与乌卢格别克讨论,因为评论的数量爆炸下面,这里是正面和负面的价值观当前最好的解决方案。

As discussed with Ulugbek, since the number of comments are exploding below, here is the current BEST solution for both positive and negative values.

由于答案和乌卢格别克Umirov ,的詹姆斯小号, KevinZ ,的