数组java的元素总和

时间:2022-06-23 12:02:58

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. I keep getting zero for my output.

编写一个名为sumArray的方法,它将一个整数数组作为参数,并返回一个等于数组中所有元素之和的整数。我的输出持续为零。

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

    return add;
}

4 个解决方案

#1


2  

You put your addition in the wrong way, it should be :

你以错误的方式添加,应该是:

add += sum[i]

#2


1  

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的每个元素一起添加。

#3


0  

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. 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.

您正在尝试向sum数组的每个元素添加等于零的add变量,然后返回仍等于零的add变量。如果你交换变量add和数组元素sum [i]的位置,你将开始在每次迭代时添加sum [i]的值。

Please make a search before you ask such a trivial question.

在你提出这样一个微不足道的问题之前,请先进行搜索。

#4


0  

shortest way i know would be :

我知道最短的方式是:

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

#1


2  

You put your addition in the wrong way, it should be :

你以错误的方式添加,应该是:

add += sum[i]

#2


1  

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的每个元素一起添加。

#3


0  

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. 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.

您正在尝试向sum数组的每个元素添加等于零的add变量,然后返回仍等于零的add变量。如果你交换变量add和数组元素sum [i]的位置,你将开始在每次迭代时添加sum [i]的值。

Please make a search before you ask such a trivial question.

在你提出这样一个微不足道的问题之前,请先进行搜索。

#4


0  

shortest way i know would be :

我知道最短的方式是:

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