如何在Java中将两个1维数组的相应值相乘?

时间:2021-07-11 12:01:44

So far, I have created 2 arrays (x and y), each with a length of 20 and are filled with random integers.
I'm trying to multiply the value of each index in one array with the value of the same index in another array, and then storing the product in a 3rd array (z).

到目前为止,我创建了2个数组(x和y),每个数组的长度为20,并且填充了随机整数。我试图将一个数组中每个索引的值乘以另一个数组中相同索引的值,然后将产品存储在第三个数组(z)中。

int z[] = new int[20];  //creating array z, which will hold the products of the corresponding indexes of arrays x and y
        for(int i = 0; i <z.length; i++)
        {
            //loop for mutliplying x and y
        }

The result: if array "x" looks like {4, 8, 2, 6, ... }, and array "y" looks like {7, 5, 1, 8, ... }, array "z" should be populated with {28, 40, 2, 48, ... }

结果:如果数组“x”看起来像{4,8,2,6,...},而数组“y”看起来像{7,5,1,8,...},则数组“z”应该是填充{28,40,2,48,...}

I have only been able to find examples on multiplying every single value between 2 arrays, but nothing on how to multiply corresponding indexes

我只能找到两个数组之间的每个单值相乘的例子,但没有关于如何乘以相应的索引的例子

Edit: Thank you, user Aominè for the solution!

编辑:谢谢你,用户Aominè的解决方案!

The equation was simply

方程式很简单

z[i] = x[i] * y[i];

1 个解决方案

#1


1  

Try something like:

尝试以下方法:

for(int i = 0; i < z.length; i++) { 
     z[i] = x[i] * y[i]; 
}

#1


1  

Try something like:

尝试以下方法:

for(int i = 0; i < z.length; i++) { 
     z[i] = x[i] * y[i]; 
}