首页 > 解决方案 > 如何将两个具有相同长度的数组相乘并返回具有这些值的新数组?

问题描述

public static double multi(double u[][]) {
    double x[] = { 1, 2, 3 };
    double y[] = { 4, 5, 6 };

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

到目前为止,这是我的代码。例如,我想与 乘以arr1[] = {1,2,3};arr2 [] = {4,5,6}; 返回相同的长度,乘以乘以arr1和的值arr2[4,10,18]像这样:1*42*53*6

还有一点很重要:任务是将它返回到一个新数组中。

标签: javaarrays

解决方案


只需声明一个z与其他两个数组大小相同的新数组。遍历它们,将每个索引值相乘并返回数组z

public static double[] multi() {
     double x[] = { 1, 2, 3 };
     double y[] = { 4, 5, 6 };

     double z[] = new double[3];

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

推荐阅读