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

问题描述 投票:1回答:2

如何以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));
}

}

java arrays multiplying
2个回答
2
投票

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

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

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


0
投票

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

public static void main(String... ars) {
    int numbersA[] = new int[10];
    int numbersB[] = new int[10];
    int numbersC[] = new int[10];
    Random rand = new Random();

    for (int i = 0; i < numbersA.length; i++) {
        numbersA[i] = rand.nextInt(10);
    }
    System.out.println(Arrays.toString(numbersA));

    for (int i = 0; i < numbersB.length; i++) {
        numbersB[i] = rand.nextInt(10);
    }

    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));
}
© www.soinside.com 2019 - 2024. All rights reserved.