/* *TestMain.cpp *功能:利用Jacobi迭代和Gauss迭代求解方程組 *時間:2013.4.1 */ #include "Jacobi.h" #include "Gauss.h" int main () { printf("Jacobi迭代的結果:\n"); Jacobi(3 , 0.0001); printf("*****************************************************\n"); printf("Gauss迭代的結果:\n"); Gauss(3,0.0001); return 0; } /* *Gauss.cpp *功能:高斯迭代 *時間:2013.4.1 */ #include "Gauss.h" void Gauss(int n , double E) { int i; // 用來循環 int k=0; //記錄迭代次數 double maxE; //設置初始值 double *a = (double *)malloc(sizeof(double)*(n+1)); for(i=1;i<=n;i++) { a[i]=0; printf("%d :X0=%f ,",k,a[i]); } printf("\n"); //存放新的解 double *temp = (double *)malloc(sizeof(double)*(n+1)); do { CalculateG(a,temp); k++; printf("%d :",k); for(i=1;i<=n;i++) { printf("X%d=%f ,",i,temp[i]); } printf("\n"); swapX(temp,a,n); maxE = fabs(temp[1]-a[1]); for(i=2;i<=n;i++) { if(maxE<fabs(temp[i]-a[i])) maxE = fabs(temp[i]-a[i]); } }while(maxE >=E); return ; } //計算x void CalculateG(double *a,double *temp) { temp[1] = -2.4-0.4*a[2]-0.2*a[3]; temp[2] = 5+0.25*temp[1]+0.5*a[3]; temp[3] = 0.3-0.2*temp[1]+0.3*temp[2]; return ; } /* *Jacobi.cpp *功能:Jacobi迭代 *時間:2013.4.1 */ #include "Jacobi.h" void Jacobi(int n , double E) { int i; // 用來循環 int k=0; //記錄迭代次數 double maxE; //設置初始值 double *a = (double *)malloc(sizeof(double)*(n+1)); for(i=1;i<=n;i++) { a[i]=0; printf("%d :X0=%f ,",k,a[i]); } printf("\n"); //存放新的解 double *temp = (double *)malloc(sizeof(double)*(n+1)); do { CalculateJ(a,temp); k++; printf("%d :",k); for(i=1;i<=n;i++) { printf("X%d=%f ,",i,temp[i]); } printf("\n"); swapX(temp,a,n); maxE = fabs(temp[1]-a[1]); for(i=2;i<=n;i++) { if(maxE<fabs(temp[i]-a[i])) maxE = fabs(temp[i]-a[i]); } }while(maxE >=E); return ; } //計算x一課本3.1爲例 void CalculateJ(double *a,double *temp) { temp[1] = -2.4-0.4*a[2]-0.2*a[3]; temp[2] = 5+0.25*a[1]+0.5*a[3]; temp[3] = 0.3-0.2*a[1]+0.3*a[2]; return ; } /* *common.cpp *功能:Jacobi和Gauss迭代公用函數 */ #include "common.h" //交換解 void swapX(double *temp,double *a,int n) { int i; double tmp; for(i=1;i<=n;i++) { tmp = temp[i]; temp[i] = a[i]; a[i] = tmp; } return ; } 相關頭文件: /* *Jacobi.h */ #include "common.h" void Jacobi(int n , double E); void CalculateJ(double *a,double *temp); /* *Gauss.h */ #include "common.h" void Gauss(int n,double E); void CalculateG(double *a,double *temp); /* *common.h */ #include <stdio.h> #include <math.h> #include <stdlib.h> void swapX(double *temp,double *a,int n);