#include <stdio.h>
#include <math.h>
#define MAXROW 30
#define MAXCOL 31
void Print(int row, int col, double a[MAXROW][MAXCOL]){
for (int i = 0; i < row; ++i){
for (int j = 0; j < col; ++j){
printf("%6.2f\t", a[i][j]);
}
putchar('\n');
}
}
int Solve(int row, int col, double a[MAXROW][MAXCOL], double x[MAXROW]){
int curRow = 0;
while (curRow < row) {
int i;
for (i = curRow; i < row; i++) {
double dividend = 0;
int j;
for (j = curRow; j < row; j++) {
if (fabs(a[i][j]) < 1e-6) j++;
else {
dividend = a[i][j];
break;
}
}
for (int k = 0; k < row+1; k++) {
if (fabs(dividend) < 1e-6) {
break;
}
else a[i][k] /= dividend;
if (i != curRow) {
a[i][k] -= a[j][k];
}
}
}
curRow++;
}
curRow = row-1;
while (curRow > 0) {
for (int i = curRow-1; i >= 0; i--) {
a[i][col-1] -= a[i][curRow] * a[curRow][col-1];
if (!(fabs(a[curRow][curRow]) < 1e-6))a[i][curRow] = 0;
}
curRow--;
}
int zeroTimes = 0;
for (int i = 0; i < row; i++) {
int j = i;
while (j < col && fabs(a[i][j]) < 1e-6) {
j++;
}
if (j != i && j == col-1) {
return 2;
}
else if (j == col) {
zeroTimes++;
}
}
if (zeroTimes != 0) {
return 3;
}
for (int i = 0; i < row; ++i){
x[i] = a[i][col-1];
}
return 1;
}
void PrintX(int row, const double x[], FILE *fp){
fprintf(fp, "\nSolutions:\n");
int k = 0;
for (k = 0; k < row; ++k){
fprintf(fp, "x%d = %.2f ", k+1, x[k]);
}
}
int main(){
double a[MAXROW][MAXCOL] = {0};
FILE *fp;
char fname[100];
while (1) {
printf("Please enter path of file:");
scanf("%s", fname);
if ((fp = fopen(fname, "r+")) != NULL) break;
else printf("Wrong path!\n");
}
int rank;
fscanf(fp, "%d", &rank);
fgetc(fp);
int row = rank, col = rank+1;
for (int i = 0; i < row; ++i){
for (int j = 0; j < col; ++j){
fscanf(fp, "%lf", &a[i][j]);
if (j != col-1) fgetc(fp);
}
}
double x[MAXROW];
int result;
result = Solve(row, col, a, x);
if (result == 1){
Print(row, col, a);
PrintX(row, x, fp);
}
else if (result == 2) fprintf(fp, "\nNo solution.\n");
else if (result == 3) fprintf(fp, "\nInfinite solutions.\n");
fclose(fp);
system("pause");
return 0;
}
Q4: N元一次方程组(矩阵)
最新推荐文章于 2021-05-19 20:17:19 发布