gpt4 book ai didi

java - 第一、第二大金额

转载 作者:行者123 更新时间:2023-12-01 23:27:27 25 4
gpt4 key购买 nike

问题是:

Write a program that prompt the user to enter 5 numbers and find the two largest values among them. If the user enters number more than 100 or less than – 100 the program should exit.

Hint: use break.

我的代码是:

import java.util.*;

public class q2 {
static Scanner scan = new Scanner (System.in);
public static void main (String[] args ) {

int num;
int max=0;//define Maximum value and save it in variable max = 0;
int secondMax=0;//define the second maximum value and save it in variable secondMax = 0;

System.out.println("Please , Enter 5 numbers between 100 and -100 "); //promet user to enter 5 numbers with the condition

for (int count=0 ; count<5 ; count++) // start loop with (for)
{
num = scan.nextInt();//user will enter number it will be repeated 5 times .

if( num > 100 || num<-100) //iv the user enter a number less than -100 or geater than 100 program will quit from loop
{
System.out.println("The number you have entered is less than -100 or greater than 100 ");//telling the user what he did
break;//End the loop if the condition ( num > 100 || num<-100) is true .
}
if(num>max )//Another condition to find the maximum number
max = num;//if so , num will be saved in (max)

if (num >= secondMax && num < max)// A condition to find the second Maximum number
secondMax = num;//And it will be saved in (secondMax)
}//End loop
System.out.println("The largest value is " + max); //Print the largest number
System.out.println("The second largest value is " + secondMax );//print the second largest number .
}//End main

}//End class

这是我的代码输出:

Please , Enter 5 numbers between 100 and -100 
20
30
60
20
-10
The largest value is 60
The second largest value is 20

第二大数字不正确 - 20,而不是 30。我做错了什么?

最佳答案

可以有两种情况,

  1. 您找到新的最大值,在本例中,更新 secondarymax 并将该数字设置为 max
  2. 您找到新的 SecondMax,仅更新 SecondMax

试试这个

if(num>secondMax&&num<max)   // case 2
{
secondMax = num
}
else if(num>max) // case 1
{
secondMax = max;
max = num;
}

关于java - 第一、第二大金额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19774894/

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