Average function without overflow exception

后端 未结 18 1750
一生所求
一生所求 2021-02-12 14:58

.NET Framework 3.5.
I\'m trying to calculate the average of some pretty large numbers.
For instance:

using System;
using System.Linq;

class Program
{
           


        
18条回答
  •  礼貌的吻别
    2021-02-12 15:39

    Simple answer with LINQ...

    var data = new[] { int.MaxValue, int.MaxValue, int.MaxValue };
    var mean = (int)data.Select(d => (double)d / data.Count()).Sum();
    

    Depending on the size of the set fo data you may want to force data .ToList() or .ToArray() before your process this method so it can't requery count on each pass. (Or you can call it before the .Select(..).Sum().)

提交回复
热议问题