简体   繁体   English

数组Java元素的总和

[英]Sum of elements of an array java

Write a method called sumArray that takes an array of integers as a parameter, and returns an integer equal to the sum of all elements in the array. 编写一个名为sumArray的方法,该方法将整数数组作为参数,并返回等于该数组中所有元素之和的整数。 I keep getting zero for my output. 我的输出一直保持为零。

public static int sumArray( int[] sum) {
    int add=0;
    for(int i=0; i< sum.length; i++) { 
       sum[i]+= add;
    }

    return add;
}

您以错误的方式添加了附件,应该是:

add += sum[i]
public static int sumArray( int[] sum) {
    int add=0;
    for (int i=0; i< sum.length; i++) {
        add+=sum[i];
    }
    return add;
}

Your variable on the left is being added with each element of sum. 您左边的变量将与sum的每个元素相加。

You are trying to add add variable that equals zero to each element of sum array, and then return add variable that still equals zero. 您试图将等于零的add变量添加到sum数组的每个元素,然后返回仍等于零的add变量。 If you swap the places of variable add and array element sum[i] , you will begin to add sum[i] 's value into add at each iteration. 如果交换变量add和数组元素sum[i] ,则将在每次迭代时将sum[i]的值addadd中。

Please make a search before you ask such a trivial question. 在提出这样一个琐碎的问题之前,请先进行搜索。

我知道的最短方法是:

int add=Arrays.stream(sum).sum();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM