我有两个二维数组,它们必须是数组,而不是 vector 。它们被声明为:
double x[4][6]; //size can be any value but the row and column
double y[6][4]; //must be the opposite of the other array
我需要能够将x的行乘以y的行,但是必须忽略x的第一行,并且必须忽略y的第一列。数据可能如下所示:
x = { { 1, 2, 3, 4, 5, 6 },
{ 5.5, 6.7, 3.3, 47.0, 1.2, 0.5 },
{ 1.2, 34.3, 66.7, 0.2 2.0, 3.7 },
{ 5.6, 6.5, 7.5, 5.7, 4.0, 1.1 } };
y = { { 1, 6.6, 3.2, 0.0 },
{ 2, 1.2, 1.1, 8.8 },
{ 3, 5.6, 4.3, 5.5 },
{ 4, 2.3, 4.1, 3.4 },
{ 5, 8.5, 1.9, 6.8 },
{ 6, 5.2, 5.3, 1 } };
因此,我需要跳过x数组的第一行,并将x行乘以y列。就像是:5.5*6.6
-> 6.7*1.2
-> 3.3*5.6
...我已经尝试了很多事情,但是我一直回到这个循环:
for (int i = 1; i < 6; i++) //I have also tried it backwards
{ //like i = 0; i < 4 and j = 1 etc
for (int j = 0; j < 4; j++)
{
cout << x[i][j] * y[j][i];
}
} //I have also tried adding a third int value for indexing
//And I could not figure that out either
这通常会导致错误的值相乘,例如:5.5*6.6
-> 6.7*3.2
-> 3.3*0.0
...我尝试以多种方式修改此循环,包括带while循环的双嵌套循环。什么都没用,有时我的结果是整数值相乘。我需要从
x[][]
跳过第一行,从y[][]
跳过第一列。然后将x[][]
中的行与y[][]
中的相应列相乘。但是,请跳过y[][]
的第一列。 最佳答案
这是正确的循环
for (int i = 1; i < 4; i++) {
for (int j = 0; j < 6; j++) {
cout << "(" << x[i][j] << " * " << y[j][i] << ") ";
}
cout << endl;
}
输出量(5.5 * 6.6) (6.7 * 1.2) (3.3 * 5.6) (47 * 2.3) (1.2 * 8.5) (0.5 * 5.2)
(1.2 * 3.2) (34.3 * 1.1) (66.7 * 4.3) (0.2 * 4.1) (2 * 1.9) (3.7 * 5.3)
(5.6 * 0) (6.5 * 8.8) (7.5 * 5.5) (5.7 * 3.4) (4 * 6.8) (1.1 * 1)
DemoUPD1:问题已更新
UPD2:但随后移至原始语句
这是更新问题的代码
#include <iostream>
using namespace std;
#define ROW 4
#define COL 6
double x[ROW][COL] = { { 1, 2, 3, 4, 5, 6 },
{ 5.5, 6.7, 3.3, 47.0, 1.2, 0.5 },
{ 1.2, 34.3, 66.7, 0.2, 2.0, 3.7 },
{ 5.6, 6.5, 7.5, 5.7, 4.0, 1.1 } };
double y[COL][ROW] = { { 1, 6.6, 3.2, 0.0 },
{ 2, 1.2, 1.1, 8.8 },
{ 3, 5.6, 4.3, 5.5 },
{ 4, 2.3, 4.1, 3.4 },
{ 5, 8.5, 1.9, 6.8 },
{ 6, 5.2, 5.3, 1 } };
int main() {
int yi = 0, yj = 1;
for (int xi = 1; xi < ROW; xi++) {
for (int xj = 0; xj < COL; xj++) {
double x_val = x[xi][xj];
double y_val = y[yi][yj];
yj = (yj + 1) % ROW == 0 ? 1 : yj + 1; // move to the next column
yi = yj == 1 ? yi + 1 : yi; // if required, move to next row
cout << "(" << x_val << " * " << y_val << ") ";
}
cout << endl;
}
return 0;
}
输出量(5.5 * 6.6) (6.7 * 3.2) (3.3 * 0) (47 * 1.2) (1.2 * 1.1) (0.5 * 8.8)
(1.2 * 5.6) (34.3 * 4.3) (66.7 * 5.5) (0.2 * 2.3) (2 * 4.1) (3.7 * 3.4)
(5.6 * 8.5) (6.5 * 1.9) (7.5 * 6.8) (5.7 * 5.2) (4 * 5.3) (1.1 * 1)
关于c++ - 将两个不同大小的2d数组相乘,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/65001304/