不懈的追求者
lz503338451
全部博文(16)
2011年(1)
2008年(15)
Diy_os
wangzong
分类: C/C++
2008-03-28 22:09:28
//此程序用于求方程的一个根//用一个点类的好处是:能够做到对各个点的封装,使之受其它的点的干扰#include<iostream.h>#include<math.h>float function(float x){ return x*x-6*x;}class Point{ public: float x; float y; public: Point() { cout<<"无参构造"<<endl; } Point(const float& a,const float& b):x(a),y(b){cout<<"有参构造"<<endl;} friend float Zero(Point& a,Point& b) { float y=a.x-(a.y*((a.x-b.x)/(a.y-b.y))); cout<<y<<endl; return y; } friend void Initialize(Point& a,Point& b) { while(1) { cout<<"请输入两个x值f(x)的符号相异(否则重新输入))"<<endl; cin>>a.x>>b.x; if(function(a.x)*function(b.x)<0) break; } a.y=function(a.x); b.y=function(b.x); }};float Solve(Point& a,Point& b){ float x=Zero(a,b); float y=function(x); Point temp(x,y); if(fabs(y)<1e-6) { return x; } else { if(temp.y*a.y>0)//换同号的点 { a.x=temp.x; a.y=temp.y; } else { b.x=temp.x; b.y=temp.y; } float result=Solve(a,b); return result;//这些返回值都是起承接作用的,将各个函数的结果连接上 }}void main(){ Point a,b; Initialize(a,b); cout<<"方程x*x-6*x=0的根是:"<<endl; cout<<Solve(a,b);}
上一篇:递归的分析
下一篇:字符记数
登录 注册