计算输入数字的最小值,最大值和平均值 [英] Calculating minimum, maximum, and average of inputted numbers

查看:90
本文介绍了计算输入数字的最小值,最大值和平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在不使用数组的情况下计算所有数字的平均值/最小值/最大值?每秒最多需要计算10,000个数字。

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.

推荐答案

是,

保留初始化为高值的最小变量,并在看到较低值时对其进行更新。

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.

以下代码不起作用边界检查(例如count> 0,总计不会溢出),但应该给您一个提示:

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;
}

这篇关于计算输入数字的最小值,最大值和平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆