01/10/2018, 00:20
Thắc mắc về overload operator bài toán ma trận
Em mới học C++ đang làm bài tập về ma trận .Em có chút thắc mắc ở chỗ xuất ma trận trong hàm định thức thì kết quả ra đúng,nhưng khi ở gần cuối hàm thì xuất ma trận ra kết quả bị sai ạ ?
![](/pictures/picfullsizes/2018/10/01/qla1538405722.png)
#include <iostream>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <iomanip>
using namespace std;
class matrix
{
private:
int rows, columns;
float **p;// bộ nhớ động cho mảng 2 chiều
float det = 1;
public:
matrix();
~matrix();
matrix(int r1, int c1);
friend ostream& operator<<(ostream& os, const matrix& x);//hàm in ma trận
friend istream& operator>>(istream& is, matrix& x);//hàm nhập ma trận
friend float dinhthuc(matrix &);
};
matrix::matrix()
{
this->rows = 0;
this->columns = 0;
this->p = NULL;
}
matrix::~matrix() // xoa bo nho
{
for (int i = 0; i<this->rows; i++)
delete[] p[i];
delete[] p;
p = NULL;
}
matrix::matrix(int r1, int c1)
{
this->rows = r1;
this->columns = c1;
this->p = new float *[r1 + 1];
for (int i = 0; i <= r1; i++)
{
this->p[i] = new float[c1 + 1];
for (int j = 0; j < c1; j++)
this->p[i][j] = 0;
}
}
istream& operator>>(istream& is, matrix& x)
{
cout << "So hang:";
is >> x.rows;
cout << "So cot:";
is >> x.columns;
x.p = new float*[x.rows + 1];
for (int i = 0; i < x.rows; i++)
{
x.p[i] = new float[x.columns + 1];
for (int j = 0; j < x.columns; j++)
{
cout << "Phan tu [" << i << "]" << "[" << j << "]" << "=";
is >> x.p[i][j];
}
}
return is;
}
ostream& operator<<(ostream& os, const matrix& x)
{
for (int i = 0; i < x.rows; i++)
{
os << "
";
for (int j = 0; j < x.columns; j++)
{
os << setw(6) << x.p[i][j];
}
}
cout << endl;
os << "
";
return os;
}
float dinhthuc(matrix &x)
{
int k, j, i = 1;
float temp;
cout << x; // kết quả ở đây thì đúng
for (i = 0; i < x.rows - 1; i++)
{
if (x.p[i][i] == 0)//xét các phần tử thuộc đường chéo chính
{
k = i + 1;
while ((k < x.rows) && (x.p[k][i] == 0))
k++;
if (k>(x.rows - 1))
{
x.det = 0;
break;
}
else
{
x.det = -x.det;
for (j = i; j < x.rows; j++)
{
temp = x.p[i][j];
x.p[i][j] = x.p[k][j];
x.p[k][j] = temp;
}
}
}
for (k = i + 1; k < x.rows; k++)
{
float a = -x.p[k][i] / x.p[i][i];
for (j = i; j < x.rows; j++)
x.p[k][j] += a*x.p[i][j];
}
}
cout << x; // Kết quả ở đây bị sai
for (i = 0; i < x.rows; i++)
x.det *= x.p[i][i];
return x.det;
}
int main()
{
matrix m1, mkq;
//matrix m1, m2, m3, m4, mkq;
cout << "
Nhap ma tran M1:" << endl;
cin >> m1;
cout << m1;
cout << "dinh thuc:" << dinhthuc(m1) << endl;
system("pause");
return 0;
}
Bài liên quan