0

我目前正在编写一个程序,用户必须输入 10 个数字,然后输出将是最大数字和最小数字。我的代码有问题,但找不到。

int highest=0, lowest=0, num=0;
Scanner scan = new Scanner(System.in);

for (int i=0; i<10; i++) {
    System.out.print("Enter a number:");
    num = scan.nextInt();
}

if (num > highest) {           
    highest = num;
}         
else if(num < lowest) {             
    lowest = num;
}

System.out.println("Highest number is: " + highest);
System.out.println("Lowest number is: " + lowest);
4

4 回答 4

11

Initialise your values differently:

int highest = Integer.MIN_VALUE;
int lowest = Integer.MAX_VALUE;

If you initialise them both to zero, you will never have a "highest" value below zero, or a "lowest" value above zero

于 2012-05-14T07:40:23.280 回答
6

You should put your two if conditions in the for loop else you will only compare the last number. And lowest shouldn't be set to 0 but to Integer.MAX_VALUE

于 2012-05-14T07:42:11.623 回答
3

您的初始化和逻辑存在一些问题:

int highest=Math.MIN_VALUE;
int lowest=Math.MAX_VALUE;
int num=0;
Scanner scan = new Scanner(System.in);


for(int i=0; i<10; i++){

   System.out.print("Enter a number:");
   num = scan.nextInt();
   if (num > highest){

    highest = num;
   }

   if(num < lowest){

    lowest = num;
   }

}



   System.out.println("Highest number is: " + highest);
   System.out.println("Lowest number is: " + lowest);

您还应该使用 2 个if条件而不是else if. 如果您只有一个数字,那么您最终可能会得到类似于highest等于您输入的某个数字的结果,而lowest仍然等于Math.MAX_VALUE。这可能会导致混乱。

于 2012-05-14T07:44:38.483 回答
1

您隐含地假设最低和最大为 0,现在可能就是这种情况,试试这个代码片段..

class Main{
        public static void main(String args[]){
                int highest=0, lowest=0, num=0;
                Scanner scan = new Scanner(System.in);
                highest = lowest = scan.nextInt();
                for(int i=1; i<10; i++){
                       System.out.print("Enter a number:");
                       num = scan.nextInt();
                       if (num > highest){
                           highest = num;
                       }
                       if(num < lowest){
                           lowest = num;
                    }
                    System.out.println("Highest number is: " + highest);
                    System.out.println("Lowest number is: " + lowest);
               }
        }
}
于 2012-05-14T07:49:23.490 回答