Friday, July 31, 2009

Solving a cubic in C - not working - why?

/*


** Solve a cubic polynomial


** By xxxxxxxxxx


*/





#include %26lt;math.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;stdio.h%26gt;








double a1,a2,a3,b,c,d,G,S,x1,x2,x3,x4, C, theta, P, Q, sign;


double acos (double x);








int main()


{








printf("Please enter the coefficient of x^2:");


scanf("%f",%26amp;a1);


printf("Please enter the coefficient of x:");


scanf("%f",%26amp;a2);


printf("Please enter the constant term:");


scanf("%f",%26amp;a3);





Q=(((a1*a1)-(3*a2))/9.0);


printf("Value for Q is:%f\n",Q);





S = ((2*(a1*a1*a1))-((9*(a1*a2))+(27*a3)))/5...


printf("Value for S is:%f\n",S);





/*theta=acos(S/sqrt(Q*Q*Q));


printf("Value for theta is:%f\n",theta);*/





P= pow ( (sqrt( (S*S)-(Q*Q*Q)+fabs(S) )), 1/3);





C = ((Q*Q*Q)-(S*S));





if (C%26gt;=0)


{


theta=acos(S/(sqrt(Q*Q*Q)));


x1 = ((-2*sqrt(Q))*(cos((theta)))/3.0) - (a1/3.0);


x2 = ((-2*sqrt(Q))*(cos((theta+2*3.1412)))/3.... - (a1/3.0);


x3 = ((-2*sqrt(Q))*(cos((theta+4*3.1412)))/3.... - (a1/3.0);


printf("First root: %f.\n", x1);

Solving a cubic in C - not working - why?
One possible problem is the use of the error-prone scanf() function. You've declared your variables as double, but you're using the float format identifier "%f". For doubles, you need "%lf".





If you're using C++, prefer to use iostreams:





double Q;


std::cout %26lt;%26lt; "Enter your number:" %26lt;%26lt; std::endl;


std::cin %26gt;%26gt; Q;


No comments:

Post a Comment