Calculating minimum, maximum, and average of inputted numbers

后端 未结 5 659
醉酒成梦
醉酒成梦 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:35

    Absolutely: all that can be computed one item at a time.

    Keep the current minimum and the current maximum, compute the running total, and the count. When you need the average, divide the running total by the count, and you'll get your answer.

    class calc {
        double minVal, maxVal, total;
        int count;
    public:
        calc()
        :   minVal(numeric_limits::max)
        ,   maxVal(numeric_limits::min)
        ,   total(0)
        ,   count(0) {
        }
        void process(double num) {
            minVal = min(minVal, num);
            maxVal = max(maxVal, num);
            total += num;
            count++;
        }
        double getAvg() {
            // TODO: Check count to be > 0 here
            return total / count;
        }
        double getMin() {
            return minVal;
        }
        double getMax() {
            return maxVal;
        }
    }
    

提交回复
热议问题