Вычисление определителя матрицы 3 порядка по Крамеру
Code
#include <stdio.h>
#include <conio.h>
void printMatrix(float** B, int n)//print the matrix
{
printf("\n");
int x ,y;
for(y=0; y<n; y++)
{
for(x=0; x<n; ++x)
printf("%7.2f", B[x][y]);
printf("\n");
}
printf("\n");
}
void swap_columns(float** B, int col1, int col2)
{
float* temp = B[col1];
B[col1] = B[col2];
B[col2] = temp;
}
void swap_rows(float** B, int row1, int row2, int n)
{
float temp;
for(int i=0; i<n; ++i)
{
temp = B[i][row1];
B[i][row1] = B[i][row2];
B[i][row2] = temp;
}
}
int main()
{
int n=3,x,y;
float **matr=new float*[n];
for(x=0;x<n;++x)
matr[x]=new float[n];
for(y=0;y<n;++y)
for(x=0;x<n;++x)
scanf("%f",&matr[x][y]);
printMatrix(matr, n);
float determ=1.0;
int sign = +1;
for(int i=0; i<n; ++i) //move along main diagonal
{
int nonull_x = 0, nonull_y = 0;
bool success_finding_nonull_element = false;
for(x = i; x<n; ++x)
for(y = i; y<n; ++y)
if(!success_finding_nonull_element && matr[x][y])
{
nonull_x = x;
nonull_y = y;
success_finding_nonull_element = true;
}
if(!success_finding_nonull_element) //no non-null elements
{
determ = 0.0;
break;
}
if(nonull_x != i)
{
swap_columns(matr, i, nonull_x);
sign = -sign;
}
if(nonull_y != i)
{
swap_rows(matr, i, nonull_y, n);
sign = -sign;
}
determ *= matr[i][i];
for(x=n-1; x>=i; --x)
matr[x][i] /= matr[i][i];
for (y=i+1; y<n; ++y)
for (x=n-1; x>=i; --x)
matr[x][y] -= matr[x][i]*matr[i][y];
}
determ *= sign;
printf("determinant = %f\n", determ);
getch();
for(x=0; x<n; ++x)
delete[] matr[x];
delete[] matr;
return 0;
}