如何执行int 数组的总和

给定10个ints的数组A ,初始化一个名为sum的局部变量,并使用循环查找数组A中所有数字的总和。

这是我提交的答案:

 sum = 0; while( A, < 10) { sum = sum += A; } 

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

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

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

上面的示例使用while循环,因为这是您采用的方法。 更合适的构造将是for循环,如Bogdan的答案。

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

 int sum = IntStream.of(a).sum(); 

甚至

 int sum = IntStream.of(a).parallel().sum(); 
 int sum=0; for(int i:A) sum+=i; 

声明变量时,需要声明其类型 – 在本例中为: int 。 你还在while循环中放了一个随机逗号。 可能值得查找Java的语法,并考虑使用可以解决这些错误的IDE。 你可能想要这样的东西:

 int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 }; int sum = 0; for(int i = 0; i < numbers.length; i++){ sum += numbers[i]; } System.out.println("The sum is: " + sum); 
 int sum = 0; for(int i = 0; i < A.length; i++){ sum += A[i]; } 

这是使用Java中的For循环解决此问题的有效方法

  public static void main(String[] args) { int [] numbers = { 1, 2, 3, 4 }; int size = numbers.length; int sum = 0; for (int i = 0; i < size; i++) { sum += numbers[i]; } System.out.println(sum); }