我正在尝试在c ++中将两个矩阵相乘,但结果不正确!
能否让我知道我的代码出了什么问题?!
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
//more detail
using namespace std;
#define WIDTH1 3
#define HEIGHT1 3
#define WIDTH2 3
#define HEIGHT2 3
#define WIDTH3 3
#define HEIGHT3 3
int A[HEIGHT1][WIDTH1];
int B[HEIGHT2][WIDTH2];
int C[HEIGHT3][WIDTH3];
int n, m;
int y = 0;
//more detail :)
int main() {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
cin >> m;
A[i][j] = m;
}
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
cin >> n;
B[i][j] = n;
}
//more detail :)
for (int i = 0; i < 3; i++)
{
int k = 0;
int sum = 0;
int sum2 = 0;
int sum3 = 0;
for (int j = 0; j < 3; j++)
{
int sum = A[i][j] * B[j][i];
sum += sum;
}
B[i][y] = sum;
y = y + 1;
for (int j = 0; j < 3; j++)
{
int sum2 = A[i][j] * B[j][i];
sum2 += sum2;
}
B[i][y] = sum2;
y = y + 1;
//more detail :)
for (int j = 0; j < 3; j++)
{
int sum3 = A[i][j] * B[j][i];
sum3 += sum3;
}
B[i][y] = sum3;
y = y + 1;
}
for (int i = 0; i < 3; i++)
for (int j = 0; j < 1; j++)
{
cout << B[i][j] <<"\t" << B[i][j+1] << "\t" << B[i][j+2] << "\n" ;
}
return 0;
//more detail :)
}
答案 0 :(得分:2)
您认为这样做是什么?
for (int j = 0; j < 3; j++)
{
int sum = A[i][j] * B[j][i];
sum += sum;
}
与您的原始sum
有关?它什么也没做。
不要重新声明相同的变量。
for (int j = 0; j < 3; j++)
{
sum += A[i][j] * B[j][i];
}
答案 1 :(得分:0)
谢谢,我只是更改了它,现在可以正常使用了
试图记住我所知道的基本知识并重新开始学习C ++的基础!!!
这是代码
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
using namespace std;
#define WIDTH1 3
#define HEIGHT1 3
#define WIDTH2 3
#define HEIGHT2 3
#define WIDTH3 3
#define HEIGHT3 3
int A[HEIGHT1][WIDTH1];
int B[HEIGHT2][WIDTH2];
int C[HEIGHT3][WIDTH3];
int n, m, sum;
int y = 0;
int main() {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
cin >> m;
A[i][j] = m;
}
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
cin >> n;
B[i][j] = n;
}
for (int c = 0; c < 3; c++) {
for (int d = 0; d < 3; d++) {
for (int k = 0; k < 3; k++) {
sum = sum + A[c][k] * B[k][d];
}
C[c][d] = sum;
sum = 0;
}
}
for (int i = 0; i < 3; i++)
for (int j = 0; j < 1; j++)
{
cout << C[i][j] <<"\t" << C[i][j+1] << "\t" << C[i][j+2] << "\n" ;
}
return 0;
}