Bai 04
Bai 04
#include <cstdlib>
using namespace std;
/*
class Matrix {
private:
float ** Matran;
int row; // so hang
int col; // so cot
public:
Matrix ()
{
do{
cout << "Nhap so hang : " ; cin >> row;
cout << "Nhap so cot : " ; cin >> col;
}
while(row == 0 && col == 0);
Matran = new float *[row];
for (int i = 0 ; i < row ; ++i)
{
Matran[i] = new float [col];
for (int j = 0; j < col; ++j) {
Matran[i][j] = rand() % 100; // Random value between 0 and 99
}
}
}
Matrix(int &m , int &n) // chi dung While
{
while (m <= 0 && n <= 0)
{
cout << "Nhap so dong :" ;
cin >> m ;
cout << "Nhap so cot :" ;
cin >> n ;
}
row = m ;
col = n ;
Matran = new float *[row];
for (int i = 0 ; i < row ; ++i)
{
Matran[i] = new float [col];
for (int j = 0; j < col; ++j) {
Matran[i][j] = rand() % 100; // Random value between 0 and 99
}
}
}
~Matrix ()
{
for (int i = 0 ; i < row ; ++i)
{
delete [] Matran[i];
}
delete [] Matran;
}
void Nhap()
{
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
cin >> Matran[i][j];
}
}
}
void Xuat()
{
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
cout << Matran[i][j] << " ";
}
cout << endl;
}
}
friend Matrix operator + (const Matrix& other)
{
Matrix result(row, col);
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
result.Matran[i][j] = Matran[i][j] + other.Matran[i][j];
}
}
return result;
}
friend Matrix operator - (const Matrix& other)
{
Matrix result(row, col);
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
result.Matran[i][j] = Matran[i][j] - other.Matran[i][j];
}
}
return result;
}
friend Matrix operator * (const Matrix& other)
{
Matrix result(row, other.col);
for (int i = 0; i < row; ++i) {
for (int j = 0; j < other.col; ++j) {
result.Matran[i][j] = 0;
for (int k = 0; k < col; ++k) {
result.Matran[i][j] += Matran[i][k] * other.Matran[k][j];
}
}
}
return result;
}
float operator()(int r, int c) const {
return Matran[r][c];
}
};
*/
#include <iostream>
#include <cstdlib> // For rand() and srand()
class Matrix {
private:
float **Matran;
int row; // số hàng
int col; // số cột
public:
Matrix() {
do {
cout << "Nhập số hàng: "; cin >> row;
cout << "Nhập số cột: "; cin >> col;
} while (row <= 0 || col <= 0);
Matrix(int m, int n) {
while (m <= 0 || n <= 0) {
cout << "Nhập số hàng: "; cin >> m;
cout << "Nhập số cột: "; cin >> n;
}
row = m;
col = n;
Matran = new float *[row];
for (int i = 0; i < row; ++i) {
Matran[i] = new float[col];
for (int j = 0; j < col; ++j) {
Matran[i][j] = rand() % 100; // Giá trị ngẫu nhiên trong khoảng từ
0 đến 99
}
}
}
~Matrix() {
for (int i = 0; i < row; ++i) {
delete[] Matran[i];
}
delete[] Matran;
}
void Nhap() {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
cout << "Nhập phần tử [" << i +1 << "][" << j +1 << "]: ";
cin >> Matran[i][j];
}
}
}
void Xuat() {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
cout << Matran[i][j] << " ";
}
cout << endl;
}
}