我试图编写一个从用户获取5个数字的java程序,并确定哪个是最大的,哪个是最小的,我遇到了逻辑问题,我无法安静地知道如何将所有5个输入数字相互比较并确定最大和最小:
import java.util.Scanner;
public class determine {
public static void main (String [] args) {
Scanner scan=new Scanner(System.in);
System.out.println("enter 5 numbers : ");
for(int i=1; i<=5; i++){
int num=scan.nextInt();
if (num is bigger than the rest)
System.out.println(num+" is the largest");
if (num is smaller than rest )
System.out.println(num+" is the smallest");
}
}
}
我解决了问题,有没有其他方法来比较数字而不是设置最小值和最大值?
import java.util.Scanner;
public class determine {
public static void main (String [] args) {
int max=-9999;
int min=9999;
Scanner scan=new Scanner(System.in);
System.out.println("enter 5 numbers : ");
for(int i=1; i<=5; i++){
int num=scan.nextInt();
if (num>max){max=num;}
if(num<min){min=num;}
}
System.out.println(max+"largest");
System.out.println(min+"smallest");
}
}
答案 0 :(得分:1)
只需使用额外的变量max
,您可以在其中存储到目前为止看到的最大数字。对于每个新号码,您只需检查新号码是否大于max
,然后将其分配给max
。最后,您将获得max
; - )
答案 1 :(得分:0)
只需初始化最小值和最大值。然后在每次迭代时,您必须对用户输入的数字进行一些测试,并相应地更新最小值和最大值。我把事情留给了???。
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
System.out.println("enter 5 numbers : ");
for(int i=1; i<=5; i++){
int num=scan.nextInt();
if (?????)
max = ????;
else if (?????)
min = ????;
}
System.out.println(max+" is the largest");
System.out.println(min+" is the smallest");
答案 2 :(得分:0)
创建一个数组
int[] numbers = new int[5];
for(int i=0; i<5; i++){
numbers[i]=scan.nextInt();
}
然后对数组进行排序;
int max=numbers[0];
for (int i=0; i<5; i++){
if (max<num[i]){
max=num[i]
}
}
System.out.println(max+" is the largest");
答案 3 :(得分:0)
以下是一般概念:
package max;
public class Max {
//assumes integers
//wrong output for min
public static void main(String[] args) {
int[] numbers = {99, 9, 502, 7, 3};
int indexOfMin = 0;
int indexOfMax = 0;
int currentNumber = numbers[0];
int min = numbers[0];
int max = numbers[0];
for (int i = 0; i < numbers.length; i++) {
currentNumber = numbers[i];
if (currentNumber >= max) {
max = currentNumber;
indexOfMax = i;
}
System.out.println("position " + i + " has a value of " + currentNumber);
System.out.println("current max of " + max + " is at position " + indexOfMax);
}
System.out.println("max value of " + max + " is at position " + indexOfMax);
System.out.println("min value of " + min + " is at position " + indexOfMin); //whoops, wrong output
}
}
我会将用户输入/输出留给您。作为思考的食物,在你这样做之后,考虑如何对数组进行排序。不要只是查找答案,尝试自己排序。在发布作业时,要明确你正在做什么以及你要求的是什么。