如何用C++求解方程ax^2+bx+c=0的解
4个回答
展开全部
#include<iostream.h>
#include<math.h>
class Equation{
float a,b,c;
public:
float x[2];
Equation(float a1=0.0,float b1=0.0,float c1=0.0)
{
a=a1;
b=b1;
c=c1;
}
~Equation(){}
long CalResult();
};
long Equation::CalResult()
{
long temp;
if ((b*b-4*a*c)==0)
{
temp=1;
x[0]=(float)(-(b/2*a));
return temp;
}
if ((b*b-4*a*c)>0)
{
temp=2;
x[0]=(-b+sqrt(b*b-4*a*c))/(2*a);
x[1]=(-b-sqrt(b*b-4*a*c))/(2*a);
return temp;
}
else
{
temp=0;
}
return temp;
}
int main()
{
float a,b,c;
char ch;
do{
cout<<"请输入一元二次方程系数a"<<endl;
cin>>a;
cout<<"请输入一元二次方程系数b"<<endl;
cin>>b;
cout<<"请输入一元二次方程系数c"<<endl;
cin>>c;
Equation *obj=new Equation(a,b,c);
cout<<"方程有"<<obj->CalResult()<<"个根"<<endl;
if (obj->CalResult()==1)
{
cout<<"X="<<obj->x[0]<<endl;
}
if (obj->CalResult()==2)
{
cout<<"X1="<<obj->x[0]<<endl;
cout<<"X2="<<obj->x[1]<<endl;
}
delete obj;
cout<<"是否继续计算?(1)"<<endl;
cin>>ch;
}while(ch=='1');
return 0;
}
#include<math.h>
class Equation{
float a,b,c;
public:
float x[2];
Equation(float a1=0.0,float b1=0.0,float c1=0.0)
{
a=a1;
b=b1;
c=c1;
}
~Equation(){}
long CalResult();
};
long Equation::CalResult()
{
long temp;
if ((b*b-4*a*c)==0)
{
temp=1;
x[0]=(float)(-(b/2*a));
return temp;
}
if ((b*b-4*a*c)>0)
{
temp=2;
x[0]=(-b+sqrt(b*b-4*a*c))/(2*a);
x[1]=(-b-sqrt(b*b-4*a*c))/(2*a);
return temp;
}
else
{
temp=0;
}
return temp;
}
int main()
{
float a,b,c;
char ch;
do{
cout<<"请输入一元二次方程系数a"<<endl;
cin>>a;
cout<<"请输入一元二次方程系数b"<<endl;
cin>>b;
cout<<"请输入一元二次方程系数c"<<endl;
cin>>c;
Equation *obj=new Equation(a,b,c);
cout<<"方程有"<<obj->CalResult()<<"个根"<<endl;
if (obj->CalResult()==1)
{
cout<<"X="<<obj->x[0]<<endl;
}
if (obj->CalResult()==2)
{
cout<<"X1="<<obj->x[0]<<endl;
cout<<"X2="<<obj->x[1]<<endl;
}
delete obj;
cout<<"是否继续计算?(1)"<<endl;
cin>>ch;
}while(ch=='1');
return 0;
}
展开全部
#include<stdio.h>
#include<math.h>
int f(double a,double b,double c,double *x1,double *x2)
{
double d=b*b-4*a*c;
if(d>0)
{
*x1=(-b+sqrt(d))/(2*a);
*x2=(-b-sqrt(d))/(2*a);
return 1;
}
else if(d==0)
{
*x1=*x2=(-b)/(2*a);
return 0;
}
else
return -1;
}
void main()
{ double a1,a2,a3,y1,y2,t;
printf("请输入要解方程的系数:\n");
scanf("%lf%lf%lf",&a1,&a2,&a3);
t=f(a1,a2,a3,&y1,&y2);
if(t>0)
printf("x1=%.10f tx2=%.10f\n",y1,y2);
else if(t==0)
printf("x1=x2=%.4f\n",y1);
else printf("此方程无解!");
}
#include<math.h>
int f(double a,double b,double c,double *x1,double *x2)
{
double d=b*b-4*a*c;
if(d>0)
{
*x1=(-b+sqrt(d))/(2*a);
*x2=(-b-sqrt(d))/(2*a);
return 1;
}
else if(d==0)
{
*x1=*x2=(-b)/(2*a);
return 0;
}
else
return -1;
}
void main()
{ double a1,a2,a3,y1,y2,t;
printf("请输入要解方程的系数:\n");
scanf("%lf%lf%lf",&a1,&a2,&a3);
t=f(a1,a2,a3,&y1,&y2);
if(t>0)
printf("x1=%.10f tx2=%.10f\n",y1,y2);
else if(t==0)
printf("x1=x2=%.4f\n",y1);
else printf("此方程无解!");
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
dfs
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |