C++一元三次方程盛金解法

以下是程序代码,这段程序可以计算一元三次方程的三个根(包括虚数根)。


#include <stdio.h>

#include <math.h>

 

int doubleEqual(double x,double y);

int sgn(double x);

void ShengJin(double a,double b,double c,double d);

void ShengJin1(double a,double b);

void ShengJin2(double a,double b,double A,double B,double delta);

void ShengJin3(double a,double b,double K);

void ShengJin4(double a,double b,double A,double B);

int main()

{

    double a,b,c,d;

    printf("Enter a,b,c,d\n");

    scanf("%lf %lf %lf %lf",&a,&b,&c,&d);

 

    ShengJin(a,b,c,d);

    return 0;

}

 

int doubleEqual(double x,double y)

{

    if(fabs(x-y)<=1e-9)

    {

         return 1;

    }

    else

    {

         return 0;

    }

}

 

void ShengJin(double a,double b,double c,double d)

{

    double A,B,C,delta;

    A=b*b-3*a*c;

    B=b*c-9*a*d;

    C=c*c-3*b*d;

    delta=B*B-4*A*C;

    if(doubleEqual(A,B)&&doubleEqual(A,0))

    {

         ShengJin1(a,b);

         return;

    }

    if(doubleEqual(delta,0))

    {

         double K=B/A;

         ShengJin3(a,b,K);

    }

    else if(delta>0)

    {

         ShengJin2(a,b,A,B,delta);

    }

    else

    {

         ShengJin4(a,b,A,B);

    }

}

 

int sgn(double x)

{

    if(x>0)

    {

         return 1;

    }

    else if(x<0)

    {

         return -1;

    }

    return 0;

}

 

void ShengJin1(double a,double b)

{

    double root=-b/(3*a);

    printf("x1=x2=x3=%f\n",root);

}

void ShengJin2(double a,double b,double A,double B,doubledelta)

{

    double y1,y2; //两个参数

    double ty1,ty2; //y1,y2分别三次方根

    double root1,rootr,rooti; //root1为实根rootr为两个虚数根的实部 rooti为两个虚数根的虚部

    y1=A*b+1.5*a*(-B+sqrt(delta));

    y2=A*b+1.5*a*(-B-sqrt(delta));

    ty1=sgn(y1)*pow(abs(y1),1.0/3);

    ty2=sgn(y2)*pow(abs(y2),1.0/3);

    root1=(-b-(ty1+ty2))/(3*a);

    rootr=(-b+0.5*(ty1+ty2))/(3*a);

    rooti=abs((0.5*sqrt(3.0))*(ty1-ty2)/(3*a));

    printf("x1=%f\n",root1);

    printf("x2=%f+%fi\n",rootr,rooti);

    printf("x3=%f-%fi\n",rootr,rooti);

}

void ShengJin3(double a,double b,double K)

{

    double root1,root2;

    root1=-b/a+K;

    root2=-K/2;

    printf("x1=%f\nx2=x3=%f\n",root1,root2);

}

void ShengJin4(double a,double b,double A,double B)

{

    double root1,root2,root3;

    double ang,T;

    T=(2*A*b-3*a*B)/(2*A*sqrt(A));

    ang=acos(T);

    root1=(-b-2*sqrt(A)*cos(ang/3))/(3*a);

    root2=(-b+sqrt(A)*(cos(ang/3)+sqrt(3.0)*sin(ang/3)))/(3*a);

    root3=(-b+sqrt(A)*(cos(ang/3)-sqrt(3.0)*sin(ang/3)))/(3*a);

    printf("x1=%f\n",root1);

    printf("x2=%f\n",root2);

    printf("x3=%f\n",root3);

}


版权所有:《mntm博客》 => 《C++一元三次方程盛金解法
本文地址:http://www.mntm520.com/post/9
除非注明,文章均为 《mntm博客》 原创,欢迎转载!转载请注明本文地址,谢谢。

暧昧贴

发表评论

    微笑 大笑 拽 大哭 奸笑 流汗 喷血 生气 囧 不爽 晕 示爱 卖萌 吃惊 迷离 爱你 吓死了 呵呵