【问题标题】:Cannot get correct max and min values of user inputs无法获得用户输入的正确最大值和最小值
【发布时间】:2014-12-31 20:14:20
【问题描述】:

我正在编写一个接受用户整数输入并显示总计、平均值、最大值和最小值的方法。

我有总工作量和平均工作量,但我得到的最大值为 2147483647,最小值为 -2147483648。

循环必须仅在用户输入 -1 时结束。

我的代码:

public static void processNumbers()
{
    Menu m = new Menu();
    clrscr();

    int count = 0; // Number of times a value has been added
    int num = 0; // The Integer that the user inputs
    int tot = 0; // The total sum of the inputs
    int avg = 0; // The average value of the inputs
    int max = Integer.MAX_VALUE; // The maximum value of the inputs
    int min = Integer.MIN_VALUE; // The minimum value of the inputs

    System.out.println ("Please enter a whole number (e.g. 150)");

    while ((num = Genio.getInteger()) != -1)
    {
        count ++;

        tot += num;
        avg = tot / count; //Calculate the average the while loop
        if(tot>max) max = tot;
        if(tot<min) min = tot;

        System.out.println("Total \t Average\t Maximum\t Minimum\n");
        System.out.println(tot + "\t" + avg + "\t\t" + max + "\t" + min + "\n");
    }
    clrscr();
    System.out.println("You entered -1, you will now return to the menu!");
    pressKey();
    m.processUserChoices();
}

【问题讨论】:

    标签: java loops while-loop


    【解决方案1】:

    我相信这个

    if(tot>max) max = tot;
    if(tot<min) min = tot;
    

    应该是

    if(num>max) max = num;
    if(num<min) min = num;
    

    还有,这个

    int max = Integer.MAX_VALUE;
    int min = Integer.MIN_VALUE;
    

    应该是

    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    

    因为没有int 小于Integer.MIN_VALUE 或大于Integer.MAX_VALUE。并且您希望将号码保留为 maxmin 而不是 total

    【讨论】:

    • 谢谢!学到了新东西,非常感谢!
    【解决方案2】:
    int max = Integer.MAX_VALUE; // The maximum value of the inputs
    int min = Integer.MIN_VALUE; // The minimum value of the inputs
    

    应该交换,因为if(tot&gt;max) 永远不会是真的。同样,if(tot&lt;min) 也永远不会为真。

    此外,如果您想获得输入的最小值和最大值,则需要将 tot 替换为 num。把它们放在一起,我们得到了

    int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;
    ...
    if(num>max) max = num;
    if(num<min) min = num;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 2018-07-08
      • 2017-06-30
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 2016-10-12
      相关资源
      最近更新 更多