gpt4 book ai didi

java - 如何从用户处获取 10 个数字并打印出最大的两个数字

转载 作者:行者123 更新时间:2023-11-30 03:16:29 25 4
gpt4 key购买 nike

如何从用户处获取 10 个号码并打印出最大的两个号码?我尝试制作一个程序,从用户那里获取 10 个数字...在获取 10 个数字之后,它将显示您输入的数字的最大数量,并将显示最大数字之前的较大数字(两个最大数字)从您输入的 10 个数字中)我无法弄清楚为什么它不起作用..全部!!

import java.util.Scanner;


public class E11 {

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner scan = new Scanner(System.in);

System.out.println("Enter Number " +0 +" : " );
float scanNumTwo = scan.nextFloat();

float scanNum = scanNumTwo;
float lastscan ;
float maxim = scanNumTwo;
float lastmax = scanNumTwo;

for(int i = 1 ; i<=9 ; i++){
System.out.println("The Last Max " +lastmax +" : " );
System.out.println("The Maximum Numer Is : "+maxim);

System.out.println("Enter Number " +i +" : " );
lastscan = scanNum;
scanNum = scan.nextFloat();

if(lastscan >= scanNum && lastscan >= maxim){
maxim = lastscan;
}
else if(scanNum >= lastscan && scanNum >= maxim){
maxim = scanNum;
}

else if (scanNum>lastscan && maxim>lastmax){
lastmax = lastscan;
}
else if (scanNum>lastmax && maxim>lastmax){
lastmax = scanNum;
}

System.out.println("The Maximum Numer Is : "+lastmax);
System.out.println("The Maximum Numer Is : "+maxim);




}
System.out.println("The Maximum Numer Is : "+lastmax);
System.out.println("The Maximum Numer Is : "+maxim);


}

}

最佳答案

您需要跟踪两个最大的数字。您可以像这样初始化它们:

float maxNumb = scan.nextFloat();
float secondMax = scan.nextFloat();
if (secondMax > maxNumb) {
float temp = maxNumb;
maxNumb = secondMax;
secondMax = temp;
}

之后,您可以扫描所有数字(为了便于阅读,不包括打印体):

for (...) {
float next = scan.nextFloat();
// if greater than max, then it's the new max and the old max is the 2nd
if (next > maxNumb) {
secondMax = maxNumb;
maxNumb = next;
}
// if it's only greater than the second, then it's the new second.
else if (next > secondMax) {
secondMax = next;
}
}

关于java - 如何从用户处获取 10 个数字并打印出最大的两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32440721/

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