//本程序基於.NET平臺,編譯環境是Microsoft Visual C++ .NET
//對於VC++6.0平臺的修改,只須把stdafx.h換成iostream.h,然後去掉主函數裏的“using namespace std”
//關於計數器的設計代碼,需要動大手術,以優化代碼,使之簡潔
#include <stdafx.h>
#include <math.h>
#define eps 1e-6 //精度
using namespace std;
int ge=1;
double f(double x) //方程
{
double p=x*x+2*x-3;
return p;
}
double gexian(double xk0,double xk) //迭代函數,割線法
{
ge++;
double xk1;
cout<<"xk0="<<xk0<<'/n'<<"xk="<<xk<<'/n';
//迭代公式
xk1=xk-f(xk)*(xk-xk0)/(f(xk)-f(xk0));
//迭代替換
xk0=xk;
xk=xk1;
//
cout<<"xk1="<<xk1<<'/n'<<endl;
//判斷是否繼續迭代運算
while(fabs(f(xk1))>eps) xk1=gexian(xk0,xk);
// cout<<"迭代次數爲:"<<ge<<endl;
return xk1;
}
double newton(double x) //迭代函數,牛頓法
{
double tem;
tem=x-(x*x+2*x-3)/(2*x+2);
return tem;
}
double main_gexian() //主函數
{
cout<<"割線法/n";
cout<<"輸入一個字母(e退出):";
char exit;//定義出口
cin>>exit;
cout<<"說明:輸入兩個不相等的數。/n";
double x_k0,x_k,tmp_1;
while(exit!='e')
{
cout<<"輸入兩個數:";//初值
cin>>x_k0>>x_k;
//根
tmp_1=gexian(x_k0,x_k);
cout<<"根爲"<<tmp_1<<'/n';
//出口
cout<<"迭代次數爲:"<<ge<<endl;
cout<<"輸入字母(e退出):";
cin>>exit;
}
return 0;
}
double main_newton() //主函數
{
cout<<"牛頓法/n";
cout<<"說明:輸入一個非-1的數。輸入-1退出……"<<'/n';
cout<<"輸入:";
double s;
cin>>s;
cout<<endl;
while(s!=-1)
{
int count1=0,count2=0;//計數值
while(s!=-1) //正區間運算
{
double tmp_x=newton(s);
double f_x=f(tmp_x);
count1++;
if(fabs(f_x)<eps)
{
cout<<'/n'<<'/n'<<"x1="<<tmp_x;
cout<<" 運算次數爲:"<<count1<<'/n'<<endl;
break;
}
else
{
cout<<"x_1="<<tmp_x<<'/n';
newton(tmp_x);
}
s=tmp_x;
};
double s0=s*(-1)-1; //將輸入數轉化到以-1爲分界點的兩個區間
if(s==0) s0=-2;
while(s0!=-1)//負區間運算
{
double tmp_y=newton(s0);
double f_y=f(tmp_y);
count2++;
if(fabs(f_y)<eps)
{
cout<<'/n'<<'/n'<<"x2="<<tmp_y;
cout<<" 運算次數爲:"<<count2<<'/n';
break;
}
else
{
cout<<"x_2="<<tmp_y<<'/n';
newton(tmp_y);
}
s0=tmp_y;
};
cout<<"/n輸入:";
cin>>s;
};
if(s==-1) cout<<"結束!";//判斷除法可行性
return 0;
}
double main()
{
char select;
while(1)
{
cout<<"選擇迭代方式/n(a爲割線法,b爲牛頓法,c退出):";
cin>>select;
cout<<'/n';
if(select=='a')
{
main_gexian();
}
else if(select=='b')
{
main_newton();
}
else if(select=='c') break;
}
return 0;
}