在乘法函数中,有两个矩阵将数据存储在一个指针索引中,但是问题是这不会显示相同的结果,请检查我的代码,如果您使用的是主函数,则Matrix Matrix::Multiply(Matrix b)
在代码中发现一些错误,请告诉我
#include <iostream>
using namespace std;
#include <stdlib.h>
// implement the functions : add, sub, mult, transpose
class Matrix {
public:
Matrix(int row, int col);
int GetData();
Matrix Transpose();
int Display();
Matrix DisplayA(Matrix c);
Matrix Add(Matrix b);
Matrix Sub();
Matrix Multiply(Matrix b);
int CompareRowCol(Matrix b);
private:
int rows, cols;
//int Term[rows][cols];
int *Term;//the add 2.6ress of a[i][j] = 0 + i * cols + j => Fig2.6
};
Matrix::Matrix(int row, int col) : rows(row), cols(col)
{
Term = new int[rows * cols];
}
int Matrix::GetData() {
int input_value;
cout << "rows = " << rows << " cols = " << cols << endl;
for (int j = 0; j < rows * cols; j++)
{
cout << "term value = ";
cin >> input_value;
cout << " " << endl;
Term[j] = input_value;
}
return 0;
}
Matrix Matrix::Transpose() {
Matrix b(cols, rows);
for (int i = 0; i < cols; i++)
{
for (int j = i; j < rows*cols; j=j+cols)
{
cout << Term[j]<<" ";
}
cout << endl;
}
return b;
}
Matrix Matrix::Multiply(Matrix b) {
if (cols != b.rows) cout << "Incompatible matrices" << endl;
Matrix c(rows, b.cols);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < b.cols; j++)
{
int sum = 0;
for (int k = 0; k < b.cols; k++)
{
sum = sum + Term[i*cols+k] * Term[k*b.cols + j];
c.Term[i*b.cols + j] = sum;
}
}
}
for (int i = 0; i < rows*b.cols; i++)
{
cout << c.Term[i] << "\t";
}
return c;
}
int Matrix::CompareRowCol(Matrix b) {
if (cols != b.rows) return 1;
else return 0;
}
int Matrix::Display() {
int n;
n = rows * cols;
for (int i = 0; i < rows; i++)
{
cout << endl;
for (int j = 0; j < cols; j++)
cout << Term[i*cols + j] << " ";
}
cout << endl;
return 0;
}
Matrix Matrix::DisplayA(Matrix c) {
int n;
n = rows * cols;
for (int i = 0; i < rows; i++)
{
cout << endl;
for (int j = 0; j < cols; j++)
cout << c.Term[i*cols + j] << " ";
}
cout << endl;
return c;
}
int main()
{
Matrix a(2, 3);
Matrix b(3, 4);
Matrix c(2, 4);
cout << "Enter first matrix: " << endl;
a.GetData();
cout << "Enter second matrix: " << endl;
b.GetData();
cout << "Display first matrix: " << endl;
a.Display();
cout << "Display second matrix: " << endl;
b.Display();
cout << "Transpose() of Matrix b" << endl;
b.Transpose();
/* If colum of first matrix in not equal to row of second matrix, asking user to enter the size of matrix again. */
if (a.CompareRowCol(b))
{
cout << "Error! column of first matrix not equal to row of second.";
cout << "Enter rows and columns for first matrix: ";
}
cout << "Multiply of Matrix a,b" << endl;
c=a.Multiply(b);
c.DisplayA(c);
system("pause");
return 0;
}