【问题标题】:How to count min,max in loop (java) [closed]如何计算循环中的最小值,最大值(java)[关闭]
【发布时间】:2012-11-21 00:29:30
【问题描述】:

我在为明天的讲座编写 1 个应用程序时遇到问题。

所以, 该程序要求用户输入数字,在输入“100”时它会停止,并显示: -平均的 -分钟 -max

我知道我需要使用哪种循环(do-while 对吗?)。 但是我应该如何在不使用数组的情况下计算平均值、最小值、最大值?

【问题讨论】:

  • 向我们展示一些代码。我们不为你工作......
  • 你真的认为我们为你工作吗...!!!
  • 大声笑,不。我只是在问如何从没有数组的循环中获取这些东西,因为我现在不知道,而且我没有代码,只有概念,我的想法。我也没有,除了 some1 会为我做那件事。我只需要提示或导航我。 -_-
  • 老实说,Minimum 很简单,只需记住当前的最低值即可。与最大值相同。平均而言,将所有数字相加并除以输入的数字数(所以只需保持一个运行总计)。就像俄佐立所说的那样。

标签: java eclipse loops while-loop min


【解决方案1】:
Step 1 : user three temp variable 
Step 2 : initialize three temp variable(min,max,avg all by 0)
Step 1 : inside the loop if temp > max ==>> max = temp
Step 1 : inside the loop if temp < min ==>> min = temp
Step 1 : avg = ( avg + temp )/i

int[] values = { .. values .. }

int min=0,max=0,avg = 0;
for(int i=1;i<=values.length;i++)
{
if(min > values[i])
min = values[i] 
if(max < values[i])
max = values[i] 
avg = ( avg + values[i] ) / i
}

【讨论】:

    【解决方案2】:

    我可以告诉你如何在没有数组的情况下计算平均最小值和最大值。但是,我不能告诉你如何计算 WITH 数组的平均最小值和最大值。

    最低限度很容易:

    int current_min
    ArrayList<int> find_min = new ArrayList<int>();
    for (int c : find_min)
        if (c < current_min)
            current_min = c;
    

    最大值有点难。你需要使用“函数”

    boolean check_if_integer_is_bigger_than_another_integer(int another_integer_to_check_against, int the_original_integer_goes_here_into_this_argument_here)
    {
        if (another_integer_to_check_against > the_original_integer_goes_here_into_this_argument_here)
        return (another_integer_to_check_against > the_original_integer_goes_here_into_this_argument_here) //Important
        return (another_integer_to_check_against > the_original_integer_goes_here_into_this_argument_here)
    }
        int current_max
        ArrayList<int> find_max = new ArrayList<int>();
        for (int c : find_max)
            if (check_if_integer_is_bigger_than_another_integer(c, current_max))
                current_max = c;
    

    我什至不想进入平均水平。您必须添加数字,而我并不完全有资格。

    【讨论】:

    • 太棒了,比我的解决方案更优雅,研究得更好!在使用 Java 时,您应该使用 CarmelCase,但您的冗长程度是正确的!
    • 谢谢。我真的应该更加专注于整个“添加”的事情。如果幸运的话,也许我会通过幼儿园。
    • 我觉得你用过数组
    • 哦,看来我确实让我将其更改为列表:因为此解决方案完全合法。
    • 哈哈,这得到了最好的答案......太棒了
    【解决方案3】:

    这是简写伪代码,因为您必须自己编写代码:

    min = max = total = user_input
    count = 0
    do {
        count++
        input = get_input
        total += input
        min or max maybe = input
    } while (input !=100)
    average = total / count
    print stuff
    

    祝你好运

    【讨论】:

    • 是的,我知道 :) 谢谢!这就是我所需要的,休息我会没有问题的;)
    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2015-03-02
    • 2013-06-08
    相关资源
    最近更新 更多