2012-03-21 87 views
2

给定数组A的10 ints,初始化一个名为sum的局部变量并使用循环找到数组A中所有数字的和。如何执行int []数组的求和

这是我的回答,我提出:

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

我没有在这个问题上的任何点。我做错了什么?

+2

查找Java for循环,这可能是您的教师希望您使用的。 – scrappedcola 2012-03-21 22:06:33

+3

你在课程中有多远? – 2012-03-21 22:07:13

+12

你做错了什么是编写一个程序,然后不运行它,看它是否编译并做了你想要的。 – 2012-03-21 22:18:14

回答

13

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

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循环,因为这是你采取的方法。如Bogdan的回答,更合适的构造是for循环。

+0

好的,谢谢我欣赏它。 – 2012-03-21 22:16:37

+0

@JordanWestlund:欢迎来到StackOverflow。如果我充分回答了您的问题,请将问题标记为已回答,以便其他用户知道他们不再需要关注它。 – StriplingWarrior 2012-03-21 22:36:58

+0

对不起,我不知道我想这么做。我能将它标记为已回答吗? – 2012-03-21 22:42:24

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

当你声明一个变量时,你需要声明它的类型 - 在这种情况下: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); 
42

一旦超出(2014年3月),你就可以使用流:

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

甚至

int sum = IntStream.of(a).parallel().sum(); 
+0

*所以*对于Java的兴奋8.我怀疑在这种情况下,你会发现'parallel'的任何性能优势。事实上,我敢打赌,这样的表现会明显变慢。 – StriplingWarrior 2013-10-15 16:32:42

+1

你会感到惊讶。下面是我所做的基准测试,显示并行版本要快得多:http://www.thecoderzone.com/arrays-and-streams – msayag 2013-10-16 23:15:21

+0

太棒了。感谢分享! – StriplingWarrior 2013-10-16 23:54:03

1

这里有一个有效的方法来解决这个问题,使用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); 
} 
+0

我没有看到这增加了现有的答案。 – Prune 2016-04-14 22:27:36