【问题标题】:Best way to calculate min, max and average input values, without knowing quantity entered? [closed]在不知道输入数量的情况下计算最小、最大和平均输入值的最佳方法? [关闭]
【发布时间】:2019-09-21 14:25:42
【问题描述】:

我需要添加代码来查找输入数字的最小值、最大值和平均值。 最好使用 arraylist 吗?

感谢您的建议。很高兴听到我将来会了解数组列表(因为我现在对它们完全不熟悉),并坚持给出的建议。再次感谢。

【问题讨论】:

  • “最佳”在什么意义上?你试过什么?您遇到的具体问题是什么?

标签: java arraylist max average min


【解决方案1】:

如果您不需要手动计算(即这不是家庭作业),那么您可以使用内置的统计功能:

DoubleStream.generate(input::nextDouble).takeWhile(v -> v != 999).summaryStatistics();

这将为您提供最小值、最大值、计数、平均值和总和,而无需您进行任何手动计算。

【讨论】:

    【解决方案2】:

    你也可以不用 ArrayList 来实现。 需要使用 MIN、MAX、SUM 和 COUNTER 变量并使用第一个用户输入初始化 MIN 和 MAX。

    当用户输入任何值时,检查 MIN、MAX 并将其添加到 SUM。

    您可以登录来计算循环的平均外侧(SUM/COUNTER)

    【讨论】:

    • @CouponCode 如果有帮助,请点赞/接受答案。
    【解决方案3】:

    如果您需要手动计算(为了了解其工作原理),您只需(以伪代码形式):

    // NOTE: this is pseudo-code only, not executable code!
    
    // start with the min set to the largest float
    float min = Float.MAX_VALUE;
    
    // start with the max set to the smallest float
    float max = Float.MIN_VALUE;
    
    // start with an average of 0 and count of 0
    float average = 0.0;
    int count = 0;
    
    // for each value input
    {
    
        // get the value from the user
        float nextValue = getValueFromUser(...);
    
        // update the min value
        if (nextValue < min) {
            min = nextValue;
        }
    
        // update the max value
        if (nextValue > max) {
            max = nextValue;
        }
    
        // recalculate the average
        float sum = average * count;
        count++;
        sum += nextValue;
        average = sum / count;
    
    } // loop until the user is done
    
    // print the min, max and average
    

    【讨论】:

    • 应在循环终止后计算平均值。
    • 是的,它会更有效,但这表明如果需要,您可以随时进行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2018-07-07
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    相关资源
    最近更新 更多