Average function without overflow exception

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

    You may try the following approach:

    let number of elements is N, and numbers are arr[0], .., arr[N-1].

    You need to define 2 variables:

    mean and remainder.

    initially mean = 0, remainder = 0.

    at step i you need to change mean and remainder in the following way:

    mean += arr[i] / N;
    remainder += arr[i] % N;
    mean += remainder / N;
    remainder %= N;
    

    after N steps you will get correct answer in mean variable and remainder / N will be fractional part of the answer (I am not sure you need it, but anyway)

提交回复
热议问题