求数组中的最大值、最小值、平均值--两种方法
public class Demo4 {
public static void main(String[] args) {
//求数组中的最大值、最小值、平均值
int[] arr = {7, 3, 5, 8, 4, 2, 8, 9};
int max = arr[0];
int min = arr[0];
int maxIndex = 0;
int minIndex = 0;
double sum = arr[0];
for (int i = 1; i < arr.length; i++) {
if(arr[i] > max){
max = arr[i];
maxIndex = i;
}
if (arr[i] < min){
min = arr[i];
minIndex = i;
}
sum += arr[i];
}
//输出最大最小值的索引位置
System.out.println("数组中的最大值 max = " + max + ",位置是:" + maxIndex);
System.out.println("数组中的最小值 min = " + min + ",位置是:" + minIndex);
System.out.println("数组中的平均值 avg = " + (sum / arr.length));
}
}
public class Demo4_1 {
public static void main(String[] args) {
int[] arr = {7, 4, 1, 2, 9, 6, 5, 100 ,8};
// 定义两个变量,分别用来记录当前找到的最大值和最小值所在位置
int maxIndex = 0;
int minIndex = 0;
//定义两个变量,用来累加元素之和
double sum = arr[0];
for (int i = 1; i < arr.length; i++) {
sum += arr[i];
// 以此让arr[i]元素与max进行比较,如果比它大就取而代之
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
//直接输出
System.out.println("数组中的最大值为:" + arr[maxIndex] + ",索引为:" + maxIndex);
System.out.println("数组中的最小值为:" + arr[minIndex] + ",索引为:" + minIndex);
System.out.println("数组中元素的平均值为:" + (sum / arr.length));
}
}