假设在高斯消除方法中矩阵的第一个值,A[0][0]=0
那么如何将矩阵"A"的第 1 行与第 2 行交换,以便获得正确的结果?
假设一个 simpel 2D 数组构建方式如下所示: 只需交换行。
#include <stdio.h>
#include <stdlib.h>
#define S_MATRIX_DIM 5
int main()
{
int **A;
int *tmp;
int i, j, entry;
entry = 0;
A = malloc(S_MATRIX_DIM * sizeof(int *));
for (i = 0; i < S_MATRIX_DIM; i++) {
A[i] = malloc(S_MATRIX_DIM * sizeof(int));
for (j = 0; j < S_MATRIX_DIM; j++) {
A[i][j] = entry++;
}
}
puts("Matrix A =");
for (i = 0; i < S_MATRIX_DIM; i++) {
for (j = 0; j < S_MATRIX_DIM; j++) {
printf("%d,", A[i][j]);
}
putchar('n');
}
tmp = A[0];
A[0] = A[1];
A[1] = tmp;
puts("Matrix A, row exchanged =");
for (i = 0; i < S_MATRIX_DIM; i++) {
for (j = 0; j < S_MATRIX_DIM; j++) {
printf("%d,", A[i][j]);
}
putchar('n');
}
for (i = 0; i < S_MATRIX_DIM; i++) {
free(A[i]);
}
free(A);
exit(EXIT_SUCCESS);
}
保留同一类型的临时值;按值交换值,例:
temp=a[i][j];
a[i][j]=a[i+1][j];
a[i+1][j]=temp;