Calculating minimum, maximum, and average of inputted numbers

后端 未结 5 626
醉酒成梦
醉酒成梦 2021-01-07 11:54

Is there a way to calculate the average/min/max of all numbers without using an array? Need to calculate up to 10,000 numbers per sec.

5条回答
  •  不思量自难忘°
    2021-01-07 12:20

    Yes,

    Keep a minimum variable that is initialized to a high value, and update it if you see a lower value.

    Do the opposite with a maximum variable.

    Add up all numbers and divide that sum by the total count to get the average.

    The following code does not do bounds checks (e.g. count > 0, total doesn't overflow) but should give you an idea:

    int minimum = // Initialize to large #, in C# would be int.MaxValue
    int maximum = // Initialize to most negative #, in C# would be int.MinValue
    int count = 0;
    int total = 0;
    
    void StatsForNewNumber(int number)
    {
        if (number < minimum) minimum = number;
        if (number > maximum) maximum = number;
        count++;
        total += number;
    }
    
    int Average()
    {
        return total / count;
    }
    

提交回复
热议问题