# Thread: Newbie - cubic polynomial program - help!

1. ## Newbie - cubic polynomial program - help!

Hi guys!

Ok first of all, I am completely new to c programming & need a bit of expert help with a program I am writing. I am required to write a c program to find the roots of a cubic polynomial. I just want to add at this point that I am NOT looking for someone to write the program for me, I'm just after a little assistance. In fact, I have written what I thought to be right, but it doesn't seem to work properly. The program compiles fine, but the problem is the way it works! There are supposed to be 3 different conditions, but when I execute the program (& input coefficients), I only get the condition where there is 'one real root & two imaginary roots'. The roots are not correct either, they have letters in the answer etc. Anyway, if anyone could have a look at my code & offer me any help as to where I am going wrong, I would be most grateful!

Cherie

2. 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.