Java 如何执行 int[] 数组的求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9813573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to perform a sum of an int[] array
提问by Jordan Westlund
Given an array A
of 10 ints
, initialize a local variable called sum
and use a loop to find the sum of all numbers in the array A
.
给定一个A
10的数组ints
,初始化一个名为的局部变量sum
并使用循环来查找数组中所有数字的总和A
。
This was my answer that I submitted:
这是我提交的答案:
sum = 0;
while( A, < 10) {
sum = sum += A;
}
I didn't get any points on this question. What did I do wrong?
在这个问题上我没有得到任何分数。我做错了什么?
采纳答案by StriplingWarrior
Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:
您的语法和逻辑在很多方面都不正确。您需要创建一个索引变量并使用它来访问数组的元素,如下所示:
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.
}
The above example uses a while
loop, since that's the approach you took. A more appropriate construct would be a for
loop, as in Bogdan's answer.
上面的示例使用了一个while
循环,因为这是您采用的方法。更合适的构造是for
循环,如 Bogdan 的回答。
回答by Bogdan Emil Mariesan
int sum = 0;
for(int i = 0; i < A.length; i++){
sum += A[i];
}
回答by Mark Rhodes
When you declare a variable, you need to declare its type - in this case: int
. Also you've put a random comma in the while
loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:
当你声明一个变量时,你需要声明它的类型 - 在这种情况下: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);
回答by kasavbere
int sum=0;
for(int i:A)
sum+=i;
回答by msayag
回答by ella2469
Here is an efficient way to solve this question using For loops in Java
这是在 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);
}