הערה (קובץ קוד)
קובץ זה הוא קובץ קוד מסוג C.
#include <stdio.h>
#include <stdbool.h>
#define N (100)
#define M (100)
void printMatrix(double a[][M], int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%.2lf", a[i][j]);
if (j != m - 1)
{
printf(" ");
}
}
printf("\n");
}
}
bool inputMatrix(double a[][M], int n, int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (scanf(" %lf", &a[i][j]) != 1)
{
return false;
}
}
}
return true;
}
void swapRows(double *r1s, double *r1e, double *r2s, double *r2e)
{
while (r1s != r1e + 1)
{
const double temp = (*r1s);
(*r1s) = (*r2s);
(*r2s) = temp;
r1s++;
r2s++;
}
}
void multiplyRow(double *rs, double *re, double scalar)
{
while (rs != re + 1)
{
(*rs) *= scalar;
rs++;
}
}
void addRows(double *r1s, double *r1e, double *r2s, double *r2e, double s)
{
while (r1s != r1e + 1)
{
(*r1s) += (s * (*r2s));
r1s++;
r2s++;
}
}
void findLeadElement(double a[][M], int n, int m, int *r, int *c, bool *res)
{
*res = false;
for (int j = 0; j < m; j++)
{
for (int i = 0; i < n; i++)
{
if (a[i][j] != 0.0)
{
*r = i;
*c = j;
*res = true;
return;
}
}
}
}
void reduceRowsRandFunctionRantFunction(const int i, const int m,
const int n, const int lead_c, double a[][M])
{
for (int k = i + 1; k < n; k++)
{
double factor = -a[k][lead_c];
if (factor != 0)
{
addRows(&a[k][0], &a[k][m - 1],
&a[i][0], &a[i][m - 1], factor);
}
}
}
void reduceRowsRantFunction(const int lead_r, const int lead_c, const int i,
const int m, const int n, double a[][M])
{
int cur_r = i + lead_r;
if (cur_r != i)
{
swapRows(&a[i][0], &a[i][m - 1],
&a[cur_r][0], &a[cur_r][m - 1]);
}
double pivot_val = a[i][lead_c];
multiplyRow(&a[i][0], &a[i][m - 1], 1.0 / pivot_val);
reduceRowsRandFunctionRantFunction(i, m, n, lead_c, a);
}
void reduceRows(double a[][M], int n, int m)
{
for (int i = 0; i < n; i++)
{
int lead_r, lead_c;
bool found;
findLeadElement(a + i, n - i, m, &lead_r, &lead_c, &found);
if (!found)
{
break;
}
reduceRowsRantFunction(lead_r, lead_c, i, m, n, a);
}
}
bool checkLengths(int n, int m, int longN, int longM)
{
if (n > 0 && n <= longN && m > 0 && m <= longM)
{
return true;
}
return false;
}
int mainHelper(double matrix[][M], int n, int m)
{
printf("Enter the matrix elements:\n");
if (!inputMatrix(matrix, n, m))
{
printf("Invalid matrix elements.\n");
return 1;
}
printf("Original Matrix:\n");
printMatrix(matrix, n, m);
reduceRows(matrix, n, m);
printf("Reduced Matrix:\n");
printMatrix(matrix, n, m);
return 0;
}
int main()
{
int n, m;
double matrix[N][M];
printf("Enter number of rows (n) and columns (m):\n");
scanf("%d %d", &n, &m);
if (!checkLengths(n, m, N, M))
{
printf("Invalid matrix size.\n");
return 1;
}
return mainHelper(matrix, n, m);
}