gpt4 book ai didi

java - 如何在for循环中找到第二大的数

转载 作者:行者123 更新时间:2023-11-29 05:10:31 26 4
gpt4 key购买 nike

public static void main(String[] args) {
int num;
int large;
int small;
int secondLarge;

Scanner scan = new Scanner(System.in);
System.out.print("Input a number: ");
num = scan.nextInt();
large = num;
small = num;
secondLarge = num;

for (int x = 9; x > 0; x--) {
System.out.print("Enter " + x + " more number: ");
num = scan.nextInt();

if (num > large) {
large = num;

}
if (num > secondLarge) {
secondLarge = num;
}

if (secondLarge > large) {
large = secondLarge;

}
if (num < small) {
small = num;

}

} System.out.println( large + " is the largest number, " + secondLarge + " is the second largest number and " + small + " is the smallest number!");
}

因此,我尝试输出最大数、第二大数和最小数。我能够获得最小和最大的,但不知道从哪里开始获得第二大的。我认为这会起作用,但它输出同样大的东西。我目前不应该使用数组,因为这是家庭作业。请不要告诉我确切的答案,但一些帮助和提示会很棒!

最佳答案

像这样初始化变量

int largest=0;
int secondlargest=0;
int smallest=Integer.MAX_VALUE;

条件应该是这样的

if(number>=largest){
secondlargest=largest;
largest=number;
}else if(number>secondlargest){
secondlargest=number;
}
if(number<smallest){
smallest=number;
}

关于java - 如何在for循环中找到第二大的数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28757536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com