Code:
#include <stdio.h>
#include <math.h>
#define PI 3.1415926536
void main(void)
{
/*declare variables*/
char rpt;
float p,q,r;
float root;
float a,b;
float A,B;
float x1,x2,x3;
float a1,b1;
float real,imag;
float angle;
printf("Cubic Polynomial Solver (form y*y*y + p*y*y + q*y + r)\n");
while(1) { /*keep looping until 'break'*/
rpt = 'T';
printf("Enter coefficients:\n");
printf("p = ");
scanf("%f",&p);
printf("q = ");
scanf("%f",&q);
printf("r = ");
scanf("%f",&r);
a=(1.0/3.0)*(3.0*q - p*p);
b=(1.0/27.0)*(2.0*p*p*p - 9.0*p*q + 27.0*r);
root=(b*b/4.0)+(a*a*a/27.0);
a1=(-b/2.0)+sqrt(root);
b1=(-b/2.0)-sqrt(root);
A=pow(a1,(1.0/3.0));
B=pow(b1,(1.0/3.0));
if(root>0.0) {
x1=A+B;
real=-x1/2.0;
imag=(A-B)*sqrt(3.0)/2.0;
printf("There is one real root of %f and two conjugate imaginary roots of %f + i*%f and %f - i*%f\n",
x1-(p/3.0),real-(p/3.0),imag,real-(p/3.0),-imag);
}
else if(root<0.0) {
angle=acos((-b/2.0)/sqrt(-a*a*a/27.0));
x1=2.0*sqrt(-a/3.0)*cos(angle/3.0);
x2=2.0*sqrt(-a/3.0)*cos((angle/3.0) + 2.0*PI/3.0);
x3=2.0*sqrt(-a/3.0)*cos((angle/3.0) + 4.0*PI/3.0);
printf("Real distinct roots are: %f, %f and %f\n",x1-(p/3.0),x2-(p/3.0),x3-(p/3.0));
}
else { /*root=0*/
x1=A+B;
x2=-x1/2.0;
printf("There is a real distinct root of %f and two equal real roots of %f\n",x1-(p/3.0),x2-(p/3.0));
}
/*check for repeat*/
printf("\nIf you wish to calculate the roots of another cubic polynomial press: Y\n");
scanf(" %c",&rpt);
if (rpt !='Y') break;
} /*end while*/
} /*end main*/
> void main(void)
main returns an int.
I don't know whether the cubic root algorithm is correct, but you should try doing things like
a=(1.0/3.0)*(3.0*q - p*p);
printf("Computed a is %f\n", a );
b=(1.0/27.0)*(2.0*p*p*p - 9.0*p*q + 27.0*r);
printf("Computed b is %f\n", b );
And compare these results with your own worked out on paper for example.