我们如何将数组的每个元素相互相乘并将每个乘积值存储在 C++ 中的数组中?

How can we multiply each elements of an array to each other and store each product values in a array in c++?

示例:假设我们有一个 arr1 [1,2,3,4] 数组,乘积将为 1x2、1x3、1x4、2x1、2x3、2x4、3x1、3x2、3x4、4x1、4x , 4x3。所以新数组将像 arr2 [2,3,4,2,6,8,3,6,12,4,8,12]。 我考虑过一起去:

for( int i=0; i<n; i++){
    for(int j=0; j<n; j++){
       arr2[i]= arr1[j] * arr1[j+1];
    }
}

但这只会乘以连续的元素而不是全部。 谁能告诉我 logic/algorithm?

在进行乘法运算之前,使用 if 语句检查 i != j

您还需要另一个索引变量来保存输出数组中的索引,您不能为此使用 i,因为它在 n 处停止。您也不能使用 i*n + j 因为您正在跳过元素(可能有所需索引的公式,但使用另一个变量更简单)。

int k = 0;
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        if (i != j) {
            arr2[k++] = arr1[i] * arr1[j];
        }
    }
}