如何执行int []数组的总和

Jor*_*und 4 java arrays loops

给定一个A10 的数组ints,初始化一个被调用的局部变量,sum并使用一个循环来查找数组中所有数字的总和A.

这是我提交的答案:

sum = 0;
while( A, < 10) {
   sum = sum += A;
}
Run Code Online (Sandbox Code Playgroud)

我对这个问题没有任何意见.我做错了什么?

msa*_*yag 47

一旦退出(2014年3月),您将能够使用流:

int sum = IntStream.of(a).sum();
Run Code Online (Sandbox Code Playgroud)

甚至

int sum = IntStream.of(a).parallel().sum();
Run Code Online (Sandbox Code Playgroud)


Str*_*ior 15

您的语法和逻辑在许多方面都不正确.您需要创建一个索引变量并使用它来访问数组的元素,如下所示:

int i = 0;        // Create a separate integer to serve as your array indexer.
while(i < 10) {   // The indexer needs to be less than 10, not A itself.
   sum += A[i];   // either sum = sum + ... or sum += ..., but not both
   i++;           // You need to increment the index at the end of the loop.
}
Run Code Online (Sandbox Code Playgroud)

上面的例子使用了一个while循环,因为这是你采用的方法.一个更合适的结构将是一个for循环,如Bogdan的答案.


kas*_*ere 8

int sum=0;
for(int i:A)
  sum+=i;
Run Code Online (Sandbox Code Playgroud)