看板 NCTU-STAT98G 關於我們 聯絡資訊
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define Num 5 void mprint(double A[Num][Num], double B[Num]); time_t t1; int main() { int i,j,k; int o_row,n_row; double A[Num][Num]; double A2[Num][Num]; double B[Num]; double B2[Num]; double pivot; double temp; srand(time(&t1)); for (i=0;i<Num;i++) { B[i] = rand()/32767.0; B2[i]= B[i]; for (j=0;j<Num;j++) { A[i][j] = rand()/32767.0; A2[i][j] = A[i][j]; } } printf("The matrix is now as following:\n"); mprint(A,B); for (i=0;i<Num;i++) { pivot = fabs(A[i][i]); o_row = i; n_row = i; for (j=i+1;j<Num;j++) { if (fabs(A[j][i])>=pivot) { pivot = fabs(A[j][i]); n_row = j; } } if (o_row != n_row) { for (k=0;k<Num;k++) { temp = A[o_row][k]; A[o_row][k] = A[n_row][k]; A[n_row][k] = temp; } temp = B[o_row]; B[o_row] = B[n_row]; B[n_row] = temp; } printf("The matrix is now as following:\n"); mprint(A,B); for (j=i+1;j<Num;j++) { temp = A[j][i]/A[i][i]; for (k=0;k<Num;k++) A[j][k] = A[j][k] - A[i][k]*temp; B[j]= B[j]-B[i]*temp; } printf("The matrix is now as following:\n"); mprint(A,B); system("pause"); temp = A[i][i]; for (j=i;j<Num;j++) A[i][j] = A[i][j]/temp; B[i]= B[i]/temp; printf("The matrix is now as following:\n"); mprint(A,B); system("pause"); } for (i=Num-1;i>0;i--) { for (j=i-1;j>=0;j--) { B[j]=B[j]-B[i]*A[j][i]; A[j][i]=0; } printf("The matrix is now as following:\n"); mprint(A,B); system("pause"); } for (i=0;i<Num;i++) { temp = 0; for (j=0;j<Num;j++) temp+=A2[i][j]*B[j]; printf("%dth:old value = %lf, new value =%lf\n",i+1,B2[i],temp); } return 0; } void mprint(double A[Num][Num], double B[Num]) { int i,j; for (i=0;i<Num;i++) { for (j=0;j<Num-1;j++) printf("%lf ",A[i][j]); printf("%lf | ",A[i][Num-1]); printf("%lf\n",B[i]); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.113.7.248