⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jacobi.cpp

📁 Jacobi和SOR算法实现
💻 CPP
字号:
#include<iostream.h>
#include<stdio.h>
#include<math.h>
#define MAXSIZE 20
#define MAX 100
#define epsilon 0.000001
int main()
{
	int n;
	int i,j,k;
	double err;
	static double a[MAXSIZE][MAXSIZE],b[MAXSIZE][MAXSIZE],c[MAXSIZE],g[MAXSIZE];
	static double x[MAXSIZE],y[MAXSIZE];
	cout<<"Please input the dim of Ax=c"<<endl;
	cin>>n;
	if(n<=0)
	{cout<<"Please input a number between 1 and "<<n;
	return 1;
	}
	cout<<"Now input the matrix a(i,j):"<<endl;
	for(i=0;i<n;i++)
		for(j=0;j<n;j++)
			cin>>a[i][j];
		cout<<"Now input the matrix c(i):"<<endl;
		for(i=0;i<n;i++)
			cin>>c[i];
		
		for(i=0;i<n;i++)
			for(j=0;j<n;j++)
			{
				b[i][j]=-a[i][j]/a[i][i];
				g[i]=c[i]/a[i][i];
			}
			for(int m=0;m<MAX;m++)
			{
				for(j=0;j<n;j++)
					y[j]=g[j];
				for(j=0;j<n;j++)
				{
					for(k=0;k<n;k++)
					{if(j!=k)
						y[j]+=b[j][k]*x[k];
					}
				}
				
				err=0;//误差
				for(j=0;j<n;j++)
					if(err<fabs(y[j]-x[j]))err=fabs(y[j]-x[j]);
					for(j=0;j<n;j++)
						x[j]=y[j];
					if(err<epsilon)
					{cout<<"the result is:"<<endl;
					for(i=0;i<n;i++)cout<<x[i]<<" ";
					cout<<endl<<"the iterations: "<<m;
					return 0;
					}
					
			}

			cout<<"no result"<<endl;
			return 1;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -