请教看一个求一元三次方程根的程序
#include <iostream>#include <math.h>
using namespace std;
class cubic
{
public:
double a,b,c,d;
double A, B, C, Y1, Y2, T, theta;
double delta,root1;
typedef struct xushu
{
double shibu;
double xubu;
}xushu;
xushu root2, root3;
void rooting()
{
cout << "Please input coefficients a, b, c and d respectively to calculate roots." << endl;
cout << "The coefficient a is: ";
cin >> a;
cout << "The coefficient b is: ";
cin >> b;
cout << "The coefficient c is: ";
cin >> c;
cout << "The coefficient d is: ";
cin >> d;
A = pow(b,2)-3*a*c;
B = b*c-9*a*d;
C = pow(c,2)-3*b*d;
delta = pow(B,2)-4*A*C;
if (A==B&&A==0&&B==0)
{
root1 = -b/(3*a);
root2.shibu = -c/b;
root3.shibu = -3*d/c;
}
else if (delta > 0)
{
Y1 = A*b+3*a*(-B+pow((pow(B,2)-4*A*C),(1.0/2)))/2;
Y2 = A*b+3*a*(-B-pow((pow(B,2)-4*A*C),(1.0/2)))/2;
root1 = (-b-pow(Y1,(1.0/3))-pow(Y2,(1.0/3)))/(3*a);
root2.shibu = (-2*b+pow(Y1,(1.0/3))+pow(Y2,(1.0/3)))/(6*a);
root2.xubu = (pow(3,(1.0/2))*(pow(Y1,(1.0/3))-pow(Y2,(1.0/3))))/(6*a);
root3.shibu = (-2*b+pow(Y1,(1.0/3))-pow(Y2,(1.0/3)))/(6*a);
root3.xubu = (-pow(3,(1.0/2))*(pow(Y1,(1.0/3))-pow(Y2,(1.0/3))))/(6*a);
cout << root1 << root2.shibu << root2.xubu << root3.shibu << root3.xubu << endl;
}
else if (delta == 0 && A != 0)
{
root1 = -b/a+(B/A);
root2.shibu = root3.shibu = -(B/A)/2;
cout << root1 << root2.shibu << root3.shibu << endl;
}
else if (delta < 0 && A>0 && T>-1 && T<1)
{
T=(2*A*b-3*a*B)/(pow(2*A,(3/2)));
theta = acos(T);
root1 = (-b-pow(2*A,(1.0/2))*cos(theta/3))/(3*a);
root2.shibu = (-b+pow(A,(1.0/2))*(cos(theta/3))+(pow(3,(1.0/2)*sin(theta/3))))/(3*a);
root3.shibu = (-b+pow(A,(1.0/2))*(cos(theta/3))-(pow(3,(1.0/2)*sin(theta/3))))/(3*a);
cout << root1 << root2.shibu << root3.shibu << endl;
}
}
}calCubic;
[ 本帖最后由 spikespiegel 于 2010-11-17 17:05 编辑 ]