#include <iostream> #include <string> #include <vector> #include <iomanip> using namespace std;
const int n=3; //设置方程组的维
float a[n][n]={10,-1,-2,-1,10,-2,-1,-1,5},x[n]={0,0,0},b[n]={7.2,8.3,4.2};
void input_data() //输入方程组的相关数据
{ cout<<"输入方程组的系数矩阵a["<<n<<"]["<<n<<"]:"<<endl; for(int i=0;i<n;i++) for(int j=0;j<n;j++) cin>>a[i][j]; cout<<"输入x[1,...,"<<n<<"]的初值:"<<endl; for(i=0;i<n;i++) cin>>x[i]; cout<<"输入b[1,...,"<<n<<"]的初值:"<<endl; for(i=0;i<n;i++) cin>>b[i]; }
void output_equation() //输出方程组
{ for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(j>0&&a[i][j]>0) cout<<"+"; cout<<a[i][j]<<" x["<<j+1<<"] "; } cout<<"="<<b[i]<<endl; } }
void main () { //input_data();
int counter; //设置计算时迭代的次数
cout<<"输入迭代的次数"<<endl; cin>>counter; system("cls"); output_equation(); int k=0,i=0; //k用来统计迭代的次数;i用来表示x的序列
float m_num1; //m_x用来保存x的原先值;m_num1用来计算j!=i的数据之和
cout<<endl; cout<<"k\t"; for(int j=0;j<n;j++) cout<<"x["<<j+1<<"]\t\t\t"; cout<<endl; cout<<k<<"\t"; k++; cout << setiosflags(ios::fixed); //和下一句结合起来用来设定小数位的位数
cout << setprecision(10); for(j=0;j<n;j++) cout<<x[j]<<"\t\t"; cout<<endl; do { m_num1=0; for(j=0;j<n;j++) { if(j!=i) m_num1=m_num1+a[i][j]*x[j]; } x[i]=(b[i]-m_num1)/a[i][i]; if(i<n-1) i++; else { cout<<k<<"\t"; for(j=0;j<n;j++) cout<<x[j]<<"\t\t"; cout<<endl; i=0; k++; }; }while(k<=counter); }
|