注册 登录
编程论坛 C++教室

求:用C++编写一个求解一元二次方程的解

sunbo0418 发布于 2007-05-04 16:40, 5990 次点击
求:用C++编写一个求解一元二次方程的解

谢了啊!
3 回复
#2
aipb20072007-05-04 17:09
直接用公式就可以啊!

不难的,自己写吧
#3
nuciewth2007-05-04 19:11
不是学过公式吗,
不过也可以用弦截法和切线两种大概估计出来(首先要知道这个根的大致分布).(插值)
#4
ifeitian2007-05-05 20:12
回复:(sunbo0418)求:用C++编写一个求解一元二次方...

#include<iostream>
#include<math.h>
using namespace std;
class funtion
{
public:
~funtion(){cout<<"求解完毕"<<endl;}
void set_value(); //输入函数
void display(); //求解函数
void show_value();//输出函数
private:
float a;
float b;
float c;
float x1;
float x2;
float r;
float i;
float pd;
};
void funtion::set_value ()
{
cout<<"输入 a b c 的值且 a b c 不可全为零"<<endl;
cin>>a;
cin>>b;
cin>>c;
}
void funtion::display ()
{
pd=b*b-4*a*c;
if(pd>0)
{
x1=-b/(2*a)+sqrt(pd)/(2*a);
x2=-b/(2*a)-sqrt(pd)/(2*a);
}
else if(pd==0)
{
x1=-b/(2*a);
x2=-b/(2*a);
}
else
{
r=-b/(2*a);
i=sqrt(-pd)/(2*a);
}
}
void funtion::show_value ()
{

if(pd>0)
cout<<"x1="<<x1<<" "<<"x2="<<x2<<endl;
else if(pd==0)
cout<<"x1="<<x1<<" "<<"x2="<<x2<<endl;
else
cout<<"x1="<<r<<'+'<<i<<"i"<<" "<<"x2="<<r<<'+'<<i<<"i"<<endl;
}
int main()
{
funtion f;
f.set_value ();
f.display ();
f.show_value ();
return 0;
}
这样可不可以?是不是太繁了?

1