相关疑难解决方法(0)

平均函数没有溢出异常

.NET Framework 3.5.
我试图计算一些相当大的数字的平均值.
例如:

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        var items = new long[]
                        {
                            long.MaxValue - 100, 
                            long.MaxValue - 200, 
                            long.MaxValue - 300
                        };
        try
        {
            var avg = items.Average();
            Console.WriteLine(avg);
        }
        catch (OverflowException ex)
        {
            Console.WriteLine("can't calculate that!");
        }
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,数学结果是9223372036854775607(long.MaxValue - 200),但我在那里得到了例外.这是因为.NET Reflector检查的平均扩展方法的实现(在我的机器上)是:

public static double Average(this IEnumerable<long> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    long num = 0L;
    long num2 = …
Run Code Online (Sandbox Code Playgroud)

.net c# algorithm average overflow

19
推荐指数
3
解决办法
8382
查看次数

标签 统计

.net ×1

algorithm ×1

average ×1

c# ×1

overflow ×1