2014-11-04 60 views
0

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

我有总计和平均工作,但我得到的最大值为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(); 
} 

回答

3

我相信这

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

+0

谢谢!学到了新东西,非常感谢! – DarkBlueMullet 2014-11-04 19:48:42

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>max)永远不会成立。同样,if(tot<min)也永远不会成立。

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

int max = Integer.MIN_VALUE; 
int min = Integer.MAX_VALUE; 
... 
if(num>max) max = num; 
if(num<min) min = num; 
相关问题