编写一个Java应用程序,计算并输出一维数组(9.8,12,45,67,23,1.98,2.55,45)中的最大值和最小值。

2024-11-25 12:26:00
推荐回答(5个)
回答1:

public class Test {
public static void main(String[] args) {
double []d={9.8,12,45,67,23,1.98,2.55,45};
double max=0;//当前最大值
double min=0;//当前最小值
for (int i = 0; i < d.length; i++) {
if(i==0) //假设第一个最大,最小
max=min=d[0];
if(d[i]>max) //大于最大
max=d[i];
if(d[i] min=d[i];
}
System.out.println("最大值:"+max);
System.out.println("最小值:"+min);
}
}

回答2:

public class Test{
public static void main(String[] args) {
double[] arr = new double[]{9.8,12,45,67,23,1.98,2.55,45};
double max = arr[0];
double min = arr[0];
for(int i = 1;i if(max max = arr[i];
}
if(min>arr[i]){
min = arr[i];
}
}
System.out.println("最大值是"+max);
System.out.println("最小值是"+min);
}
}

回答3:

public static void main(String[] args) {
int[] a = { 12, 4, 22, 3, 90, 316, 72 };
int max = a[0];
int min = a[0];
for (int i = 1; i < a.length; i++) {
if (max < a[i]) {
max = a[i];
}
if (min > a[i]) {
min = a[i];
}
}
System.out.println(max);
System.out.println(min);
}

回答4:

用Arrays.sort()先排序,再输出首尾元素就行!

回答5:

啊,来晚了