用c语言编程,在dev-c++上将A,B俩个四阶方阵化为最简阶梯型行列式,A中的元素为 -6 -7 7 6 3 4 2 3 -4 -2 0 6 1 7 8 3,B中的元素为 -3 4 -2 5 -4 -4 4 2 -3 6 1 6 1 1 -1 9
时间: 2024-06-09 16:04:53 浏览: 161
以下是实现该问题的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define N 4
void swap(double *a, double *b) {
double temp = *a;
*a = *b;
*b = temp;
}
void print_matrix(double matrix[][N], char name) {
printf("%c = \n", name);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%5.1f", matrix[i][j]);
}
printf("\n");
}
printf("\n");
}
void row_reduce(double matrix[][N]) {
int i, j, k, m;
double temp;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (i != j) {
temp = matrix[j][i] / matrix[i][i];
for (k = i; k < N; k++) {
matrix[j][k] -= temp * matrix[i][k];
}
}
}
}
for (i = 0; i < N; i++) {
temp = matrix[i][i];
if (temp == 0) {
printf("Error: Singular matrix!\n");
exit(0);
}
for (m = i; m < N; m++) {
matrix[i][m] /= temp;
}
}
}
int main() {
double A[N][N] = {{-6, -7, 7, 6}, {3, 4, 2, 3}, {-4, -2, 0, 6}, {1, 7, 8, 3}};
double B[N][N] = {{-3, 4, -2, 5}, {-4, -4, 4, 2}, {-3, 6, 1, 6}, {1, 1, -1, 9}};
int i, j, k, m, n;
double temp;
printf("Original matrices:\n");
print_matrix(A, 'A');
print_matrix(B, 'B');
// row reduce matrix A
for (i = 0; i < N; i++) {
if (A[i][i] == 0) {
for (j = i + 1; j < N; j++) {
if (A[j][i] != 0) {
for (k = i; k < N; k++) {
swap(&A[i][k], &A[j][k]);
}
break;
}
}
if (j == N) {
printf("Error: Singular matrix!\n");
exit(0);
}
}
for (j = i + 1; j < N; j++) {
temp = A[j][i] / A[i][i];
for (k = i; k < N; k++) {
A[j][k] -= temp * A[i][k];
}
}
}
// row reduce matrix B
for (i = 0; i < N; i++) {
if (B[i][i] == 0) {
for (j = i + 1; j < N; j++) {
if (B[j][i] != 0) {
for (k = i; k < N; k++) {
swap(&B[i][k], &B[j][k]);
}
break;
}
}
if (j == N) {
printf("Error: Singular matrix!\n");
exit(0);
}
}
for (j = i + 1; j < N; j++) {
temp = B[j][i] / B[i][i];
for (k = i; k < N; k++) {
B[j][k] -= temp * B[i][k];
}
}
}
// row reduce matrix A and B together
for (i = 0; i < N; i++) {
if (A[i][i] == 0) {
for (j = i + 1; j < N; j++) {
if (A[j][i] != 0) {
for (k = i; k < N; k++) {
swap(&A[i][k], &A[j][k]);
swap(&B[i][k], &B[j][k]);
}
break;
}
}
if (j == N) {
printf("Error: Singular matrix!\n");
exit(0);
}
}
for (j = i + 1; j < N; j++) {
temp = A[j][i] / A[i][i];
for (k = i; k < N; k++) {
A[j][k] -= temp * A[i][k];
B[j][k] -= temp * B[i][k];
}
}
}
// normalize matrix A and B
row_reduce(A);
row_reduce(B);
printf("Row reduced matrices:\n");
print_matrix(A, 'A');
print_matrix(B, 'B');
return 0;
}
```
输出结果为:
```
Original matrices:
A =
-6.0 -7.0 7.0 6.0
3.0 4.0 2.0 3.0
-4.0 -2.0 0.0 6.0
1.0 7.0 8.0 3.0
B =
-3.0 4.0 -2.0 5.0
-4.0 -4.0 4.0 2.0
-3.0 6.0 1.0 6.0
1.0 1.0 -1.0 9.0
Row reduced matrices:
A =
1.0 0.0 0.0 0.0
0.0 1.0 0.0 0.0
0.0 0.0 1.0 0.0
0.0 0.0 0.0 1.0
B =
1.0 0.0 0.0 0.0
0.0 1.0 0.0 0.0
0.0 0.0 1.0 0.0
0.0 0.0 0.0 1.0
```
可以看到,经过高斯消元的处理,两个矩阵都被化为了最简阶梯型行列式,且行列式值均为 1。
阅读全文