确定最高和最低数字

确定最高和最低数字

本文介绍了确定最高和最低数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently writing a program where the user must input 10 numbers and then the output will be the highest number and the lowest number. There is something wrong in my code but couldn't find it.

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);


推荐答案

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

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

这篇关于确定最高和最低数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:16