如何以 arrayA 的第一个值乘以 arrayB 的最后一个值的方式将两个数组相乘?

How can I multiplicate two arrays in a way that the first value of arrayA multiply the last value of arrayB?

如何以 arrayA 的第一个值乘以 arrayB 的最后一个值的方式将两个数组相乘?

public static void main(String[] args) throws IOException {
    int numbersA[] = new int[5];
    int numbersB[] = new int[5];
    int numbersC[] = new int[5];

    for (int i = 0; i < numbersA.length; i++) {
        System.out.print("Please insert a number for the first array: ");
        numbersA[i] = Integer.parseInt(in.readLine());
    }
    System.out.println(Arrays.toString(numbersA));

    for (int i = 0; i < numbersB.length; i++) {
        System.out.print("Please insert a number for the second array: ");
        numbersB[i] = Integer.parseInt(in.readLine());
    }
    System.out.println(Arrays.toString(numbersB));

    System.out.print("The multiplication of the two arrays (the first one with the last one and consecutively) are: ");
    for (int i = 0; i < numbersC.length; i++) {
        numbersC[i] = numbersA[i] * numbersB[(numbersB.length) - 1 - i];
    }
    System.out.println(Arrays.toString(numbersC));
}

}

您需要从第二个数组中获取逆向索引:

for (int i = 0; i < numbersC.length; i++) {
    numbersC[i] = numbersA[i] * numbersB[numbersC.length - 1 - i];
}
System.out.println(Arrays.toString(numbersC));

当然,这个循环依赖于所有 3 个长度相同的数组。

numbersA[ ] 的第一个元素(即索引 0)应乘以 numbersB[ ][=17 的最后一个元素(即索引 9) =]数组。类似地,numbersA[] 的第二个元素(即索引 1)应乘以 numbersB[] 的倒数第二个元素(即索引 8)。如下图所示:

public static void main(String... ars) {

    System.out.println("enter the length of arrays");
    Scanner sc = new Scanner(System.in);

    int len = sc.nextInt();


    int numbersA[] = new int[len];
    int numbersB[] = new int[len];
    int numbersC[] = new int[len];

    Random rand = new Random();

    System.out.println("enter the values of first array");
    for (int i = 0; i < numbersA.length; i++) {
        numbersA[i] = sc.nextInt();
    }
    System.out.println(Arrays.toString(numbersA));

    System.out.println("enter the values of second array");
    for (int i = 0; i < numbersB.length; i++) {
        numbersB[i] = sc.nextInt();
    }

    System.out.println(Arrays.toString(numbersB));


    out.println("The multiplication of the two arrays (the first one with the last one and consecutively) are: ");
    for (int i = 0; i < numbersC.length; i++) {
        numbersC[i] = numbersA[i] * numbersB[(numbersB.length)-1-i];
    }

    System.out.println(Arrays.toString(numbersC));
}

请尝试使用您已完成的相同代码,并且在我检查时工作正常。

public class 测试{

public static void main(String[] args) {
int numbersA[] = {1,2,3,4,5};
int numbersB[] = {5,4,3,2,1};
int numbersC[] = new int[5];


System.out.print("The multiplication of the two arrays (the first one with the last one and consecutively) are: ");
for (int i = 0; i < numbersC.length; i++) {
    numbersC[i] = numbersA[i] * numbersB[(numbersB.length) - 1 - i];
        System.out.println(numbersC[i]);
}

} }