2014-11-04 2 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. И вы хотите сохранить номер как max и min не total.

+0

Спасибо! Узнал что-то новое, высоко ценимое! – DarkBlueMullet

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) также никогда не будет правдой.

Кроме того, вы должны заменить tot на num, если хотите получить минимальное и максимальное количество входов. Собирая все это вместе, мы получаем

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