#include <iostream.h>
#include <stdio.h>
#include <math.h>
//////////////////函数--用卡丹公式解一元三次方程/////////////////
void fun(double a,double b,double c,double d,
double *real_y1,double *real_y2,double *real_y3,
double *imag_y1,double *imag_y2,double *imag_y3)
{
double p,q,r,u,v,g,h,fai;
p=(3.0*a*c-b*b)/(3*a*a);
q=(2.0*pow(b,3.0)-9*a*b*c+27.0*a*a*d)/(27.0*pow(a,3.0));
r=b/(3.0*a);
h=pow(q/2.0,2.0)+pow(p/3.0,3.0);
g=sqrt(h);
if(h>=0)
{
if(-q/2.0+g<0)
u=-pow(fabs(-q/2.0+g),1.0/3.0);
else
u=pow((-q/2.0+g),1.0/3.0);
if(-q/2.0-g<0)
v=-pow(fabs(-q/2.0-g),1.0/3.0);
else
v=-pow((-q/2.0-g),1.0/3.0);
if(h==0)
{
*real_y1=u+v-r; *imag_y1=0;
*real_y2=-(u+v)/2-r; *imag_y2=0;
*real_y3=-(u+v)/2-r; *imag_y3=0;
}
else
{
*real_y1=u+v-r; *imag_y1=0;
*real_y2=-(u+v)/2; *imag_y2=sqrt(3.0)*(u-v)/2;
*real_y3=-(u+v)/2; *imag_y3=-sqrt(3.0)*(u-v)/2;
}
}
else
{
fai=acos((-q/2)/(sqrt(pow(fabs(p),3)/27)));
*real_y1=2*sqrt(fabs(p)/3.0)*cos(fai/3.0)-r;
*real_y2=-2*sqrt(fabs(p)/3.0)*cos((fai+3.1415926)/3.0)-r;
*real_y3=-2*sqrt(fabs(p)/3.0)*cos((fai-3.1415926)/3.0)-r;
*imag_y1=0; *imag_y2=0; *imag_y3=0;
}
}
//////////////////////////////////主函数////////////////////////////////
void main()
{
double a,b,c,d;
double real_x1,real_x2,real_x3;
double *preal_x1=&real_x1;
double *preal_x2=&real_x2;
double *preal_x3=&real_x3;
double imag_x1,imag_x2,imag_x3;
double *pimag_x1=&imag_x1;
double *pimag_x2=&imag_x2;
double *pimag_x3=&imag_x3;
cout<<"请输入方程的系数a,b,c,d:"<<"\n"<<endl;
cout<<"系数a=";
cin>>a;
cout<<endl;
cout<<"系数b=";
cin>>b;
cout<<endl;
cout<<"系数c=";
cin>>c;
cout<<endl;
cout<<"系数d=";
cin>>d;
cout<<endl;
fun(a,b,c,d,preal_x1,preal_x2,preal_x3,pimag_x1,pimag_x2,pimag_x3);
cout<<" "<<" "<<"根的实部"<<" "<<"根的虚部"<<"\n"<<endl;
printf("x1 %.5f %.5f\n\n",real_x1,imag_x1);
printf("x2 %.5f %.5f\n\n",real_x2,imag_x2);
printf("x3 %.5f %.5f\n\n",real_x3,imag_x3);
}
评论