Java 带数组的点积
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18775744/
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
Dot product with arrays
提问by Sophia Ali
In class we had to write a small code using Dot Product to find the sum of two arrays(array a and array b). I have written my code however when I run it it does not give me the answer. My professor said my loop was wrong however I do not think it is. Is the part that says i<a.length
not allowed in a for loop parameter? Because even if I set it to n it still does not give me the sum.
在课堂上,我们必须使用 Dot Product 编写一个小代码来查找两个数组(数组 a 和数组 b)的总和。我已经编写了我的代码,但是当我运行它时,它并没有给我答案。我的教授说我的循环错了,但我认为不是。i<a.length
在 for 循环参数中表示不允许的部分?因为即使我将它设置为 n 它仍然不会给我总和。
Here is my code:
这是我的代码:
public class arrayExample {
public static void main (String [] args) {
int[] a = {1,2,2,1};
int[] b = {1,2,2,1};
int n = a.length;
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[n] * b[n];
}
System.out.println(sum);
}
}
采纳答案by arshajii
n
isn't the loop control variable, it's a.length
which is an out of bounds index. You probably meant
n
不是循环控制变量,它a.length
是越界索引。你可能是说
sum += a[i] * b[i];
And, although it does not matter directly, you probablymeant your for
-loop to be
而且,虽然这并不重要,但您可能意味着您的for
-loop 是
for (int i = 0; i < n; i++)
(I would assume that's the reason you have n
in the first place.)
(我认为这就是您n
首先拥有的原因。)
回答by Mansi Edi
public class arrayExample
{
public static void main (String [] args)
{
int[] a = {1,2,2,1};
int[] b = {1,2,2,1};
int n = a.length;
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += a[i] * b[i];
}
System.out.println(sum);
}
}