Vyrieste n-linearnych rovnic pomocou Cramerovho pravidla...
Akosi sa neviem pohnut
Kód: Vybrať všetko
#include <iostream>
#include <vector>
#include <algorithm>
//deklaracie
using namespace std;
typedef vector<double>Vect;
typedef vector<Vect>Matr;
int fact(int a),i,j,p,nb;
double determ,matica[50][50],pomocna[50][50],vysledky[50],D[50];
//vypocet determinantu pre lubovolnu stvorcovu maticu
int det(){
int counter = 0,ve1 = 0;Vect row(nb);
Vect determinant;
Matr a;
double product = 1;
determ = 0;
//nacitanie matice
for(i = 0; i < nb; i++){
for(j = 0; j < nb; j++)
row[j]=matica[i][j];
a.push_back(row);
}
//vypocet determinantu
vector<int>vec;
for(i = 1; i <= nb; i++)
vec.push_back(i);
vector<int>::iterator iter1 = vec.begin();
vector<int>::iterator iter2 = vec.end();
for(i = 0; i < fact(nb); i++){
vector<int>vec1(nb);
copy(vec.begin(), vec.end(), vec1.begin());
for(int i = 0; i < vec1.size(); i++)
for(int j = i; j < vec1.size(); j++)
if(vec1[j]<vec1[i])
counter++;
for(int w = 0; w < nb; w++){
ve1 = (vec1[w])-1;
product *= (a[w][ve1]);
}
if(counter%2!=0)
product = (- product);
determinant.push_back(product);
counter = 0;
product = 1;
next_permutation(iter1, iter2);
}
//zapisanie determinantu do premennej
for(int x = 0; x < determinant.size(); x++)
determ += determinant[x];
}
//pomocna funkcia pre vypocet determinantu
int fact(int a){
if(a<=1)
return a;
return (a * fact(a - 1));
}
//hlavny program
int main(){
int p,r;
cout << "Zadaj pocet rovnic: ";
cin >> nb;
printf("Rovnicu (napr.) ax + by =c zadaj v tvare a b c.\n\n");
//nacitanie rovnic (matice a vysledkov) z klavesnice
for(i = 0; i < nb; i++){
cout << "Zadaj " << i+1 << ".rovnicu: ";
for(j = 0; j < nb+1; j++){
if(j!=nb)
cin >> matica[i][j];
else
cin >> vysledky[i];
}
}
//vypocet a zistenie ci hlavny D nie je nulovy, pretoze delit nulou sa neda
det();
if(determ==0){
printf("Determinant je rovny 0. Neda sa pouzit Cramer!\n");
system("pause");
exit(0);
}
//ak nie je rovny 0 tak program pokracuje
D[0]=determ;
//vytvorenie pomocnej matice
for(p = 0; p < nb; p++)
for(j = 0; j < nb; j++)
pomocna[p][j]=matica[p][j];
//vypis zakladnej matice a jej determinantu
for(r = 0; r < nb; r++){
cout<<endl;
for(j = 0; j < nb; j++)
cout << matica[r][j];
}
cout << endl << "D=" << D[0]<<endl;
//vymena stlpcov v matici za vektor vysledkov a vypocet determinantov
for(p=0;p<nb;p++){
for(j = 0; j < nb; j++)
matica[j][p]=vysledky[j];
det();
D[p+1]=determ;
for(r = 0; r < nb; r++){
cout<<endl;
for(j = 0; j < nb; j++)
cout << matica[r][j];
}
cout << endl << "D["<<p+1<<"]=" << D[p+1] << endl;
for(r = 0; r < nb; r++)
for(j = 0; j < nb; j++)
matica[r][j] = pomocna[r][j];
}
//Pouzitie cramerovho pravidla: delenie determinantov
printf("\nVysledny vektor hodnot je:\n");
for(i=0;i<nb;i++)
cout<<i+1<<".hodnota: "<<D[i+1]<<" / "<<D[0]<<" alebo "<<D[i+1]/D[0]<<endl;
printf("\n");
system("pause");
}