1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <iostream>
#include <vector>
using namespace std;
typedef vector<vector<double>> Matrice;
Matrice lire_matrice();
void affiche_matrice(const Matrice& M);
Matrice somme(const Matrice& M1, const Matrice& M2);
//-------------------------------------------------------------
int main()
{
Matrice M1(lire_matrice()), M2(lire_matrice());
if(M1[0].size() != M2.size()) {
cout <<"Somme des matrices impossible !" << endl;
} else {
cout << "Resultat :" << endl;
affiche_matrice(somme(M1, M2));
}
return 0;
}
//--------------------------------------------------------------
Matrice lire_matrice()
{
cout << "Saisie d'une matrice :" << endl;
size_t lignes;
do{
cout << "Nombre de lignes :";
cin >> lignes;
} while (lignes < 1);
size_t colonnes;
do{
cout << "Nombre de colonnes :";
cin >> colonnes;
} while (colonnes < 1);
Matrice M(lignes, vector<double>(colonnes));
for (size_t i(0); i < lignes; ++i) {
for (size_t j(0); j < colonnes; ++j){
cout << " M[" << i+1 << "," << j+1 << "]=";
cin >> M[i][j];
}
}
return M;
}
//-----------------------------------------------------------------
Matrice somme(const Matrice& M1, const Matrice& M2)
{
// crée la Matrice prod è la bonne taille *et* l'initialise
// avec des zéros :
Matrice som(M1.size(), vector<double>(M2[0].size()));
for (size_t i(0); i < M1.size(); ++i)
for (size_t j(0); j < M2[0].size(); ++j)
for (size_t k(0); k <M2.size(); ++k)
som[i][j] += M1[i][j] + M2[k][j];
return som;
}
//--------------------------------------------------------------------
void affiche_matrice(const Matrice& M)
{
for (auto ligne : M){
for (auto element : ligne){
cout << element << " ";
}
cout << endl;
}
} |