确定最高和最低数字[英] Determine the highest and lowest number

问题描述

我目前正在编写一个程序,用户必须输入 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);

推荐答案

以不同的方式初始化你的值:

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

如果将它们都初始化为零,则永远不会有低于零的"最高"值或高于零的"最低"值

本文地址:https://www.itbaoku.cn/post/978660.html