Разработать программу для обработки матриц. Программа должна выполнять следующие действия: суммы, вычитания, умножения двух матриц. Матрицы должны храниться в двух разных файлах. То есть, при запуске программы, необходимо считать из файлов две матрицы и уже после этого производить вычисления. Результат вывести на экран.
К сожалению, решения данной задачи пока нет. Если Вы решили эту задачу, сообщите нам, и мы выложим её на сайте.
E-mail : admin@cppstudio.com
Комментарии
RaldenProg
#include <iostream> #include <cstdlib> #include <cmath> #include <fstream> using namespace std; int main() { setlocale(LC_ALL, "rus"); ifstream fin("matrix1.txt"); int mtr1[5][5]; if (!fin.is_open()) // если файл не открыт cout << "Файл не может быть открыт!\n"; // сообщить об этом else { cout<<"1 матрица"<<endl; for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { fin>>mtr1[i][j]; cout<<mtr1[i][j]<<"\t"; } cout<<endl; } } cout<<endl; fin.close(); fin.open("matrix2.txt"); int mtr2[5][5]; if (!fin.is_open()) // если файл не открыт cout << "Файл не может быть открыт!\n"; // сообщить об этом else { cout<<"2 матрица"<<endl; for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { fin>>mtr2[i][j]; cout<<mtr2[i][j]<<"\t"; } cout<<endl; } } fin.close(); cout<<endl; //сложение матриц cout<<"сумма"<<endl; int summtr[5][5]; for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { summtr[i][j]=mtr1[i][j]+mtr2[i][j]; cout<<summtr[i][j]<<"\t"; } cout<<endl; } cout<<endl; //разность матриц cout<<"разность"<<endl; int razmtr[5][5]; for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { razmtr[i][j]=mtr1[i][j]-mtr2[i][j]; cout<<razmtr[i][j]<<"\t"; } cout<<endl; } cout<<endl; //умножение матриц cout<<"произведение"<<endl; int proizmtr[5][5]; for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { proizmtr[i][j]=0; } } for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { for(int g=0;g<5;g++) { proizmtr[i][j]+=mtr1[i][g]*mtr2[g][j]; } cout<<proizmtr[i][j]<<"\t"; } cout<<endl; } return 0; }Дима Дорошенко
#include <iostream> #include <fstream> #include <string> using namespace std; void Dim(string str, int &a, int &b) { a = 1; b = 1; int i = 0; while(str[i] != '\n') { if(str[i] == ' ') b++; i++; } while(str[i] != '') { i++; if(str[i] == '\n' || str[i] == '') a++; } } void Convert_to_int(string str, int *matr, int A, int B) { int znak = 0; int c = 0; int a = 0; int i = 0; int j = -1; do { j++; if(str[j] == '-') znak = 1; if(str[j] >= '0' && str[j] <= '9') { c = 1; i = i * 10 + (str[j] - '0'); } else if(c == 1) { c = 0; if(znak == 1) i *= -1; matr[a] = i; a++; i = 0; } }while(str[j] != ''); } void Sum(int *m1, int *m2, int m, int n, int c, int d) { if(m != c) { cout << "Error!!!" << endl; return; } if(n != d) { cout << "Error!!!" << endl; return; } int *result = new int[100]; for(int i = 0; i < (m * n); i++) result[i] = m1[i] + m2[i]; int j = 0; cout << "Result:" << endl; for(int i = 0; i < (m * n); i++) { if(j >= n) { cout << endl; j = 0; } cout << result[i] << " "; j++; } } void Dif(int *m1, int *m2, int m, int n, int c, int d) { if(m != c) { cout << "Error!!!" << endl; return; } if(n != d) { cout << "Error!!!" << endl; return; } int *result = new int[100]; for(int i = 0; i < (m * n); i++) result[i] = m1[i] - m2[i]; int j = 0; cout << "Result:" << endl; for(int i = 0; i < (m * n); i++) { if(j >= n) { cout << endl; j = 0; } cout << result[i] << " "; j++; } } void Multi(int *m1, int *m2, int m, int n, int c, int d) { if(n != c) { cout << "Error!!!" << endl; return; } int e = m, f = d; // разрешение новой матрицы int a = 0; int **mas1 = new int*[m]; for(int i = 0; i < m; i++) mas1[i] = new int[n]; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) mas1[i][j] = m1[a++]; a = 0; int **mas2 = new int*[c]; for(int i = 0; i < c; i++) mas2[i] = new int[d]; for(int i = 0; i < c; i++) for(int j = 0; j < d; j++) mas2[i][j] = m2[a++]; int **result = new int*[e]; for(int i = 0; i < e; i++) result[i] = new int[f]; for(int i = 0; i < e; i++) { for(int j = 0; j < f; j++) { result[i][j] = 0; for(int k = 0; k < n; k++) { int temp = mas1[i][k] * mas2[k][j]; result[i][j] += temp; } } } //int j = 0; cout << "Result:" << endl; for(int i = 0; i < e; i++) { for(int j = 0; j < f; j++) cout << result[i][j] << " "; cout << endl; } } void Parser(string str) { string name1; string name2; int i = 0; while(str[i] == ' ') i++; while(str[i] != ' ' && str[i] != '+' && str[i] != '-' && str[i] != '*') { name1 += str[i]; i++; } cout << name1 << endl; while(str[i] == ' ' || str[i] == '+' || str[i] == '-' || str[i] == '*') i++; while(str[i] != ' ' && str[i] != '+' && str[i] != '-' && str[i] != '*' && str[i] != '') { name2 += str[i]; i++; } cout << name2 << endl << endl; ifstream matrix(name1); if(!matrix.is_open()) { cout << "Error!!! File " << name1 << " not exist!!!" << endl; while(!matrix.is_open()) { matrix.close(); name1.clear(); cout << "Please repeat: "; getline(cin, name1); matrix.open(name1); } } name1.clear(); char k; while(!matrix.eof()) { if(matrix.get(k)) name1 += k; } cout << "Matrix 1:" << endl << name1 << endl << endl; matrix.close(); matrix.open(name2); if(!matrix.is_open()) { cout << "Error!!! File " << name2 << " not exist!!!" << endl; while(!matrix.is_open()) { matrix.close(); name2.clear(); cout << "Please repeat: "; getline(cin, name2); matrix.open(name2); } } name2.clear(); while(!matrix.eof()) { if(matrix.get(k)) name2 += k; } cout << "Matrix 2:" << endl << name2 << endl << endl; matrix.close(); int m = 1, n = 1; // размерность первой матрицы int c = 1, d = 1; // размерность второй матрицы Dim(name1, m, n); // подсчет размерности Dim(name2, c, d); cout << m << '~' << n << " " << c << '~' << d << endl; int *m1 = new int[100]; int *m2 = new int[100]; Convert_to_int(name1, m1, m, n); Convert_to_int(name2, m2, c, d); // теперь в массивах записаны матрицы int f = str.find('+'); if(f > 0) { Sum(m1,m2,m,n,c,d); return; } f = str.find('-'); if(f > 0) { Dif(m1,m2,m,n,c,d); return; } f = str.find('*'); if(f > 0) { Multi(m1,m2,m,n,c,d); return; } } int main() { while(1) { system("cls"); string Str; //char Operation; cout << "Enter the matrix (Example: name1.txt + name2.txt): "; getline(cin, Str); Parser(Str); system("pause"); } }Дима Дорошенко
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Dim(string str, int &a, int &b)
{
a = 1;
b = 1;
int i = 0;
while(str[i] != ‘\n’)
{
if(str[i] == ‘ ‘)
b++;
i++;
}
while(str[i] != »)
{
i++;
if(str[i] == ‘\n’ || str[i] == »)
a++;
}
}
void Convert_to_int(string str, int *matr, int A, int B)
{
int znak = 0;
int c = 0;
int a = 0;
int i = 0;
int j = -1;
do
{
j++;
if(str[j] == ‘-‘)
znak = 1;
if(str[j] >= ‘0’ && str[j] <= ‘9’)
{
c = 1;
i = i * 10 + (str[j] — ‘0’);
}
else
if(c == 1)
{
c = 0;
if(znak == 1)
i *= -1;
matr[a] = i;
a++;
i = 0;
}
}while(str[j] != »);
}
void Sum(int *m1, int *m2, int m, int n, int c, int d)
{
if(m != c)
{
cout << «Error!!!» << endl;
return;
}
if(n != d)
{
cout << «Error!!!» << endl;
return;
}
int *result = new int[100];
for(int i = 0; i < (m * n); i++)
result[i] = m1[i] + m2[i];
int j = 0;
cout << «Result:» << endl;
for(int i = 0; i < (m * n); i++)
{
if(j >= n)
{
cout << endl;
j = 0;
}
cout << result[i] << » «;
j++;
}
}
void Dif(int *m1, int *m2, int m, int n, int c, int d)
{
if(m != c)
{
cout << «Error!!!» << endl;
return;
}
if(n != d)
{
cout << «Error!!!» << endl;
return;
}
int *result = new int[100];
for(int i = 0; i < (m * n); i++)
result[i] = m1[i] — m2[i];
int j = 0;
cout << «Result:» << endl;
for(int i = 0; i < (m * n); i++)
{
if(j >= n)
{
cout << endl;
j = 0;
}
cout << result[i] << » «;
j++;
}
}
void Multi(int *m1, int *m2, int m, int n, int c, int d)
{
if(n != c)
{
cout << «Error!!!» << endl;
return;
}
int e = m, f = d; // разрешение новой матрицы
int a = 0;
int **mas1 = new int*[m];
for(int i = 0; i < m; i++)
mas1[i] = new int[n];
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
mas1[i][j] = m1[a++];
a = 0;
int **mas2 = new int*[c];
for(int i = 0; i < c; i++)
mas2[i] = new int[d];
for(int i = 0; i < c; i++)
for(int j = 0; j < d; j++)
mas2[i][j] = m2[a++];
int **result = new int*[e];
for(int i = 0; i < e; i++)
result[i] = new int[f];
for(int i = 0; i < e; i++)
{
for(int j = 0; j < f; j++)
{
result[i][j] = 0;
for(int k = 0; k < n; k++)
{
int temp = mas1[i][k] * mas2[k][j];
result[i][j] += temp;
}
}
}
//int j = 0;
cout << «Result:» << endl;
for(int i = 0; i < e; i++)
{
for(int j = 0; j < f; j++)
cout << result[i][j] << » «;
cout << endl;
}
}
void Parser(string str)
{
string name1;
string name2;
int i = 0;
while(str[i] == ‘ ‘)
i++;
while(str[i] != ‘ ‘ && str[i] != ‘+’ && str[i] != ‘-‘ && str[i] != ‘*’)
{
name1 += str[i];
i++;
}
cout << name1 << endl;
while(str[i] == ‘ ‘ || str[i] == ‘+’ || str[i] == ‘-‘ || str[i] == ‘*’)
i++;
while(str[i] != ‘ ‘ && str[i] != ‘+’ && str[i] != ‘-‘ && str[i] != ‘*’ && str[i] != »)
{
name2 += str[i];
i++;
}
cout << name2 << endl << endl;
ifstream matrix(name1);
if(!matrix.is_open())
{
cout << «Error!!! File » << name1 << » not exist!!!» << endl;
while(!matrix.is_open())
{
matrix.close();
name1.clear();
cout << «Please repeat: «;
getline(cin, name1);
matrix.open(name1);
}
}
name1.clear();
char k;
while(!matrix.eof())
{
if(matrix.get(k))
name1 += k;
}
cout << «Matrix 1:» << endl << name1 << endl << endl;
matrix.close();
matrix.open(name2);
if(!matrix.is_open())
{
cout << «Error!!! File » << name2 << » not exist!!!» << endl;
while(!matrix.is_open())
{
matrix.close();
name2.clear();
cout << «Please repeat: «;
getline(cin, name2);
matrix.open(name2);
}
}
name2.clear();
while(!matrix.eof())
{
if(matrix.get(k))
name2 += k;
}
cout << «Matrix 2:» << endl << name2 << endl << endl;
matrix.close();
int m = 1, n = 1; // размерность первой матрицы
int c = 1, d = 1; // размерность второй матрицы
Dim(name1, m, n); // подсчет размерности
Dim(name2, c, d);
cout << m << ‘~’ << n << » » << c << ‘~’ << d << endl;
int *m1 = new int[100];
int *m2 = new int[100];
Convert_to_int(name1, m1, m, n);
Convert_to_int(name2, m2, c, d);
// теперь в массивах записаны матрицы
int f = str.find(‘+’);
if(f > 0)
{
Sum(m1,m2,m,n,c,d);
return;
}
f = str.find(‘-‘);
if(f > 0)
{
Dif(m1,m2,m,n,c,d);
return;
}
f = str.find(‘*’);
if(f > 0)
{
Multi(m1,m2,m,n,c,d);
return;
}
}
int main()
{
while(1)
{
system(«cls»);
string Str;
//char Operation;
cout << «Enter the matrix (Example: name1.txt + name2.txt): «;
getline(cin, Str);
Parser(Str);
system(«pause»);
}
}
Иван Незамутдинов
#include <iostream> #include <fstream> void openFiles(std::ifstream &file1, std::ifstream &file2, const char * name1, const char * name2); // Функция открытия файлов template<class T> void fillMatrixs(std::ifstream &filse1, std::ifstream &filse2, T ** matrix1, T ** matrix2, std::size_t N, std::size_t M); //Функция заполнения матриц template<class T> void summMatrixs(T ** matrix1, T ** matrix2, std::size_t N, std::size_t M); //Суммма матриц template<class T> void differenceMatrixs(T ** matrix1, T ** matrix2, std::size_t N, std::size_t M); //разность матриц template<class T> void multiplicationMatrixs(T ** matrix1, T ** matrix2, std::size_t N, std::size_t M); //умножение матриц int main(void) { double ** matrix1, ** matrix2; const std::size_t N = 3, M = 3; //Размеры матриц const char * nameFile1 = "E:/one.txt", * nameFile2 = "E:/two.txt"; std::ifstream file1, file2; // Выделение памяти под матрицы matrix1 = new double *[N]; matrix2 = new double *[N]; for(std::size_t i = 0; i < N; ++i) { matrix1[i] = new double [M]; matrix2[i] = new double [M]; } openFiles(file1, file2, nameFile1, nameFile2); //Открываем файлы с значениями матриц fillMatrixs(file1, file2, matrix1, matrix2, N, M); //Заполняем наши матрицы значениями из файла summMatrixs(matrix1, matrix2, N, M); //Функция суммирования матриц differenceMatrixs(matrix1, matrix2, N, M); //Функция разности матриц multiplicationMatrixs(matrix1, matrix2, N, M); //Функция умножения матриц deleteMemory(matrix1, matrix2, N); // Освобождаем выделенную память return 0; } template<class T> void newMemory(T ** matrix1, T ** matrix2, std::size_t N, std::size_t M) { matrix1 = new T *[N]; matrix2 = new T *[N]; for(std::size_t i = 0; i < N; ++i) { matrix1[i] = new T [M]; matrix2[i] = new T [M]; } } template<class T> void deleteMemory(T ** matrix1, T ** matrix2, std::size_t N) //Выделение памяти { for(std::size_t i = 0; i < N; ++i) { delete [] matrix1[i]; delete [] matrix2[i]; } delete [] matrix1; delete [] matrix2; } void openFiles(std::ifstream &file1, std::ifstream &file2, const char * name1, const char * name2) //Открытие файлов { file1.open(name1); file2.open(name2); if(!file1.is_open() && !file2.is_open()) { std::cout << "Error open filse" << std::endl; return; } std::cout << "Files open" << std::endl; } template<class T> //Заполнение значениями матрицы void fillMatrixs(std::ifstream &file1, std::ifstream &file2, T ** matrix1, T ** matrix2, std::size_t N, std::size_t M) { T temp; for(std::size_t i = 0; i < N && !file1.eof() ; ++i) { for(std::size_t j = 0; j < M; ++j) { file1 >> temp; matrix1[i][j] = temp; std::cout << matrix1[i][j] << "\t\t"; } std::cout << std::endl; } for(std::size_t i = 0; !file2.eof() ; ++i) { for(std::size_t j = 0; j < M; ++j) { file2 >> temp; matrix2[i][j] = temp; std::cout << matrix2[i][j] << "\t\t"; } std::cout << std::endl; } } template<class T> //Сумма матриц void summMatrixs(T ** matrix1, T ** matrix2, std::size_t N, std::size_t M) { std::cout << std::endl; std::cout << "SUMM" << std::endl; T matrixResult[N][M]; for(std::size_t i = 0; i < N; ++i) { for(std::size_t j = 0; j < M; ++j) { matrixResult[i][j] = matrix1[i][j] + matrix2[i][j]; std::cout << matrixResult[i][j] << "\t\t"; } std::cout << std::endl; } } template<class T> //Разность матриц void differenceMatrixs(T ** matrix1, T ** matrix2, std::size_t N, std::size_t M) { std::cout << std::endl; std::cout << "DIFFERENCE" << std::endl; T matrixResult[N][M]; for(std::size_t i = 0; i < N; ++i) { for(std::size_t j = 0; j < M; ++j) { matrixResult[i][j] = matrix1[i][j] - matrix2[i][j]; std::cout << T(matrixResult[i][j]) << "\t\t"; } std::cout << std::endl; } } template<class T> //Умножение матриц void multiplicationMatrixs(T ** matrix1, T ** matrix2, std::size_t N, std::size_t M) { std::cout << std::endl; std::cout << "MULTIPLICATION" << std::endl; T matrixResult[N][M]; for(std::size_t i = 0; i < N; ++i) { for(std::size_t j = 0; j < M; ++j) { matrixResult[i][j] = 0; //v - движение по вертикали, g - движение по горизонтали for(std::size_t v = 0, g = 0; v < N && g < M; ++v, ++g) { T temp = matrix1[i][g] * matrix2[v][j]; // Переумножение и схожение элементов горизонтали и вертикали matrixResult[i][j] += temp; } std::cout << matrixResult[i][j] << " \t\t"; } std::cout << std::endl; } }gornyyvladimir
#include <vcl.h> #include <iostream.h> #include <vector> #include <iterator> #include <iomanip> #include <fstream> #pragma hdrstop #pragma argsused void OpenFile(std::vector<std::vector<double> > & matrix, char *s); void matrixAddition(std::vector<std::vector<double> > matrix1,std::vector<std::vector<double> > matrix2); void matrixSubtraction(std::vector<std::vector<double> > matrix1,std::vector<std::vector<double> > matrix2); void matrixMultiplication(std::vector<std::vector<double> > matrix1,std::vector<std::vector<double> > matrix2); int main(int argc, char* argv[]) { std::vector<std::vector<double> > matrix1; std::vector<std::vector<double> > matrix2; bool progExit = true; while(progExit) { char key; cout<<"Menu: \n"<<"1 - Open matrix from file\n"<<"2 - Addition\n" <<"3 - Subtraction\n"<<"4 - Multiplication\n" <<"0 - Exit\n"; cin>>key; switch (key) { case '1': OpenFile(matrix1,"MATRIX1.txt"); OpenFile(matrix2,"MATRIX2.txt"); break; case '2': matrixAddition(matrix1,matrix2); break; case '3': matrixSubtraction(matrix1,matrix2); break; case '4': matrixMultiplication(matrix1,matrix2); break; case '0': progExit = false; break; default: cout<<"Error put number from menu\n"; } } system("pause"); return 0; } void OpenFile(std::vector<std::vector<double> > & matrix, char *s) { matrix.clear(); ifstream fin(s); if(fin.is_open()) { cout<<"All ok\n"; std::vector<double> temp; size_t col=1, row=0; char tmp; while((fin.get(tmp)) && (tmp!='\n')) { if(tmp == ' ') { col++; } } fin.seekg(0); while(!fin.eof()) { for(size_t i=0; i<col; i++) { double tmp1; fin>>tmp1; temp.push_back(tmp1); } matrix.push_back(temp); row++; temp.clear(); } for(size_t i=0;i<row;i++) { for(size_t j=0; j<col; j++) { cout<<matrix.at(i).at(j)<<' '; } cout<<endl; } } else { cout<<"Error\n"; } fin.close(); } void matrixAddition(std::vector<std::vector<double> > matrix1,std::vector<std::vector<double> > matrix2) { size_t col1,row1,col2,row2; row1=matrix1.size(); col1=matrix1.at(0).size(); row2=matrix2.size(); col2=matrix2.at(0).size(); if((col1 == col2) && (row1 == row2)) { double result; for(size_t i=0; i<row1; i++) { for(size_t j=0; j<col1; j++) { result=matrix1.at(i).at(j) + matrix2.at(i).at(j); cout<<result<<' '; } cout<<endl; } } else { cout<<"Error, not equal matrix size\n"; } } void matrixSubtraction(std::vector<std::vector<double> > matrix1,std::vector<std::vector<double> > matrix2) { size_t col1,row1,col2,row2; row1=matrix1.size(); col1=matrix1.at(0).size(); row2=matrix2.size(); col2=matrix2.at(0).size(); if((col1 == col2) && (row1 == row2)) { double result; for(size_t i=0; i<row1; i++) { for(size_t j=0; j<col1; j++) { result=matrix1.at(i).at(j) - matrix2.at(i).at(j); cout<<result<<' '; } cout<<endl; } } else { cout<<"Error, not equal matrix size\n"; } } void matrixMultiplication(std::vector<std::vector<double> > matrix1,std::vector<std::vector<double> > matrix2) { size_t col1,row1,col2,row2; row1=matrix1.size(); col1=matrix1.at(0).size(); row2=matrix2.size(); col2=matrix2.at(0).size(); if(col1 == row2) { for (size_t row = 0; row < row1; row++) { for (size_t col = 0; col < col2; col++) { // Multiply the row of A by the column of B to get the row, column of product. double result = 0; for (size_t inner = 0; inner < row2; inner++) { result += matrix1.at(row).at(inner) * matrix2.at(inner).at(col); } cout << result << " "; } cout << "\n"; } } else { cout<<"Error\n"; } }Arthur
#include<iostream> #include<fstream> #include<iomanip> #include<cstdlib> using namespace std; class Matrix { private: float** mass; int m, n; public: Matrix() //конструктор без параметров { mass = NULL; m = 0; n = 0; } //-------------------------------------------------------------------------- Matrix(int str, int stl) //конструктор с двумя параметрами { m = str; n = stl; setMatrix(); } //---------------------------------------------------------------------------- Matrix(Matrix& cop) //конструктор копирования { mass = cop.mass; m = cop.m; n = cop.n; } //-------------------------------------------------------------------------------- ~Matrix() //деструктор { for(int i = 0; i<m; i++) delete[]mass[i]; } //----------------------------------------------------------------------------- void getSize() //устанавливаем размер матрицы { while(true) { cout<<"\nЧисло строк: "; cin>>m; if(cin.good() && m>0 && m <= 20) //если все хорошо { cin.sync(); //чистим буфер break; //выходим из цикла } cin.clear(); //сброс битов ошибок cout<<"\nНеправильный ввод данных\n"; cin.sync(); } while(true) { cout<<"\nЧисло столбцов: "; cin>>n; if(cin.good() && n>0 && n <= 20) { cin.sync(); break; } cin.clear(); cout<<"\nНеправильный ввод данных\n"; cin.sync(); } setMatrix(); //строим матрицу } //--------------------------------------------------------------------------- void setMatrix() { mass = new float*[m]; for(int i = 0; i<m; i++) mass[i] = new float[n]; for(int i = 0; i<m; i++) //обнуляем матрицу явным образом for(int j = 0; j<n; j++) mass[i][j] = 0; } //---------------------------------------------------------------------------- void readMatrix() const //считывание матрицы { char adres[30]; while(true) { cout<<"\nВведите адрес файла содержащего матрицу: "; cin>>adres; ifstream inmatr(adres); if(inmatr) { cout<<"\nСчитывание матрицы...\n"<<endl; for(int x = 0; x<m; x++) for(int y = 0; y<n; y++) inmatr>>mass[x][y]; cin.sync(); break; } cout<<"\nНевозможно открыть файл!\n"; cin.clear(); cin.sync(); } } //----------------------------------------------------------------------------- void showMatrix() const //показать матрицу { for(int x = 0; x<m; x++) { for(int y = 0; y<n; y++) cout<<setw(4)<<mass[x][y]; cout<<"\n\n"; } } //------------------------------------------------------------------------------- Matrix& operator =(const Matrix& pr)//перегрузка оператора присваивания { if(mass) //если указатель указывает не на NULL for(int i = 0; i<m; i++) //чистим область памяти delete[]mass[i]; if(this == &pr) //если самоприсваивание return *this; mass = pr.mass; m = pr.m; n = pr.n; return *this; } //------------------------------------------------------------------------------------------- Matrix operator*(Matrix& r) const //перегрузка оператора умножения { if( n == r.m) //если число столбцов 1-й матрицы равны числу строк второй { Matrix rezult(m, r.n); //создаем матрицу for(int z=0; z<m; z++) for(int x=0; x<r.n; x++) for(int y=0; y<n; y++) rezult.mass[z][x] += mass[z][y] * r.mass[y][x]; return rezult; } cout<<"\nНесовместимы размеры матриц!\n"; exit(1); } //---------------------------------------------------------------------- Matrix operator-(Matrix& r) const//перегрузка оператора вычитания { if( m == r.m && n == r.n ) //если размеры матриц одинаковы { Matrix rezult(m, n); for(int x=0; x<m; x++) for(int y=0; y<n; y++) rezult.mass[x][y] = mass[x][y] - r.mass[x][y]; return rezult; } cout<<"\nМатрицы имеют разные размеры!\n"; exit(1); } //------------------------------------------------------------------------ Matrix operator+(Matrix& r) const//перегрузка оператора сложения { if( m == r.m && n == r.n ) { Matrix rezult(m, n); for(int x=0; x<m; x++) for(int y=0; y<n; y++) rezult.mass[x][y] = mass[x][y] + r.mass[x][y]; return rezult; } cout<<"\nМатрицы имеют разные размеры!\n"; exit(1); } }; //////////////////////////////////////////////////////////////////// int main() { setlocale(LC_CTYPE, "rus"); Matrix matrix1; Matrix matrix2; cin.unsetf(ios::skipws); //не игнорировать разделители cout<<"Введите размеры и адрес матрицы 1\n"; matrix1.getSize(); //запрашиваем размеры матрицы и строим матрицу matrix1.readMatrix(); //считываем матрицу cout<<"\nМатрица 1:\n\n"; matrix1.showMatrix(); //показываем матрицу cout<<"Введите размеры и адрес матрицы 2\n"; matrix2.getSize(); matrix2.readMatrix(); cout<<"Матрица 2:\n\n"; matrix2.showMatrix(); Matrix rezult_matr; while(true) { cin.sync(); char ch; cout<<"\nВыберите действие: " <<"\n'-' - для вычитания матриц" <<"\n'+' - для сложения матриц" <<"\n'*' - для умножения матриц" <<"\n'0' - для выхода" <<"\nВаш выбор: "; cin>>ch; switch(ch) { case '-': { rezult_matr = matrix1 - matrix2; cout<<"\nРезультат вычитания матриц:\n"<<endl; rezult_matr.showMatrix(); break; } case '+': { rezult_matr = matrix1 + matrix2; cout<<"\nРезультат сложения матриц:\n"<<endl; rezult_matr.showMatrix(); break; } case '*': { rezult_matr = matrix1 * matrix2; cout<<"\nПроизведение матриц:\n\n"; rezult_matr.showMatrix(); break; } case '0': return 0; default: cout<<"\nНеизвестное действие\n"; } } return 0; }