Java--求数组中的最大值、最小值、平均值--两种方法

求数组中的最大值、最小值、平均值--两种方法

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));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值