Average function without overflow exception

后端 未结 18 1990
一生所求
一生所求 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:43

    Perhaps you can reduce every item by calculating average of adjusted values and then multiply it by the number of elements in collection. However, you'll find a bit different number of of operations on floating point.

    var items = new long[] { long.MaxValue - 100, long.MaxValue - 200, long.MaxValue - 300 };
    var avg = items.Average(i => i / items.Count()) * items.Count();
    

提交回复
热议问题