java中数组求最大值,最小值,中和,平均

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中数组求最大值,最小值,中和,平均相关的知识,希望对你有一定的参考价值。

public class LxJavaCX {

 public static void main(String[] args) {

       

// 定义一个整型数组,并赋初值

int[] nums = new int[] { 49,61, 23, 4, 74,160, 13, 148, 20 ,150};

       

int max = nums[0]; // 假定最大值为数组中的第一个元素

int min = nums[0]; // 假定最小值为数组中的第一个元素

double sum = 0;// 累加值

double avg = 0;// 平均值

       

for (int i = 0; i < nums.length; i++) { // 循环遍历数组中的元素

       // 如果当前值大于max,则替换max的值

if(nums[i]>max){

max = nums[i];

}

       // 如果当前值小于min,则替换min的值

       if(nums[i]<min){

        min = nums[i];

       }

       // 累加求和

       sum = sum+nums[i];

       

}

       

       // 求平均值

      avg = sum/nums.length;

       

System.out.println("数组中的最大值:" + max);

System.out.println("数组中的最小值:" + min);

System.out.println("数组中的平均值:" + avg);

}

}


以上是关于java中数组求最大值,最小值,中和,平均的主要内容,如果未能解决你的问题,请参考以下文章