Average function without overflow exception

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

    If you're willing to sacrifice precision, you could do something like:

    long num2 = 0L;
    foreach (long num3 in source)
    {
        num2 += 1L;
    }
    if (num2 <= 0L)
    {
        throw Error.NoElements();
    }
    double average = 0;
    foreach (long num3 in source)
    {
        average += (double)num3 / (double)num2;
    }
    return average;
    

提交回复
热议问题