如何在处理中将两个数组中的值相乘

时间:2018-10-21 04:47:01

标签: java arrays processing

做硬件并面对这个问题:

“编写一个函数,将两个数组中的值相乘,然后将结果作为新数组返回。”

这是我到目前为止的代码...每当我尝试在处理过程中运行它时,我都会遇到许多错误消息,而且我仍然不确定我的代码是如何不正确的。如果您能提供帮助,我将不胜感激。

public int weightedSum(int[5] a, int [6] b);
{
  int value;
  int sum;

  for (int i =0; i < a.length; i++)
  {
    value += a[i]* b[i];
    //sum = sum + value;
  }
  return sum;
}
int [] data; 

void setup () {
  size (500, 500);
  data= new int[5];
  data [0] = 5; 
  data[1] = 10;
  data[2] = 15;
  data [3] = 20;
  data [4] = 25;

int data [] new int[6]
data = new int [6];
data [0] = 2;
data[1] = 4;
data [2] = 6;
data [3] = 8;
data [4]= 10;

1 个答案:

答案 0 :(得分:0)

public static int weightedSum(int[] one, int[] two) {
    if (one.length != two.length)
        throw new IllegalArgumentException("Arrays should be with same size");

    int sum = 0;

    for (int i = 0; i < one.length; i++)
        sum += one[i] * two[i];

    return sum;
}

您的客户端代码可能如下所示:

int[] one = { 1, 2, 3, 4, 5 };
int[] two = { 6, 7, 8, 9, 10 };
int weightedSum = weightedSum(one, two);    // weightedSum = 130