数组中值的总和和平均值

时间:2016-08-21 08:19:39

标签: java arrays

我想问一下如何添加值并查找数组中值的平均值。我尝试过多次搜索,但是我能找到一些解释如何用简单的代码完成所有这些的事情,这样我就可以理解一个像我这样的新程序员。如果有人能告诉我如何操作并解释所使用的代码,那将是很棒的。提前致谢:>

4 个答案:

答案 0 :(得分:2)

我为其他人留下正常的答案。对于java人来说,我们走吧!

 public static void main(String[] args) {
    int myarr[]={1,2,3,4,4,5,6,5,7,8,4};
    IntSummaryStatistics statisticalData=Arrays.stream(myarr).summaryStatistics();
    System.out.println("Average is " + statisticalData.getAverage());
    System.out.println("Sum is " + statisticalData.getSum());
}

其他数据如count,minimum element,maximum element也可以从IntSummaryStatistics对象中获取

答案 1 :(得分:2)

public static void main(String args[]) {
    Scanner s = new Scanner(System.in); //Define Scanner class object which will aid in taking user input from standard input stream.
    int a[] = new int[10]; //Define an array
    int i,sum = 0;
    for(i = 0; i < 10; i++) {
        a[i] = s.nextInt(); //Take the arrays elements as input from the user
    }
    for(i = 0; i < 10; i++) { //Iterate over the array using for loop. Array starts at index 0 and goes till index array_size - 1
        sum = sum + a[i]; //add the current value in variable sum with the element at ith position in array. Store the result in sum itself.
    }
    double avg = (double) sum / 10; //Compute the average using the formula for average and store the result in a variable of type double (to retain numbers after decimal point). The RHS of the result is type casted to double to avoid precision errors
    System.out.print(sum + " " + avg); //print the result
}

答案 2 :(得分:1)

首先,您必须获取一系列数字。迭代数组中的所有数字并将数字添加到变量中。因此,在迭代后,您将获得数字的总和。现在将总和除以数字的数量(这意味着数组的大小)。这样你就可以获得平均值。

int[] numbers = {10, 20, 15, 56, 22};
double average;
int sum = 0;

for (int number : numbers) {
    sum += number;
}

average = sum / (1.0 * numbers.length);
System.out.println("Average = " + average);

你也可以这样迭代:

for (int i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}

答案 3 :(得分:0)

void sumAndAverage(int a[]){
    if(a!=null&&a.length>0{
    int sum=0;
    //traverse array and add it to sum variable
    for(int i=0;i<a.length;i++){
        sum=sum+a[i];
    }
    double avg=(1.0*sum)/a.length;
    System.out.println("sum= "+sum);
    System.out.println("average= "+avg);
    }
}