I have to write a programme in C++ Builder 4 that will calculate all roots of a quadratic equation, and am struggling to produce complex roots, it gives a message of
the first complex root = -1.5+ i+.AN
the second complex root = -1.5- i+.AN

it also gives the worng answer when the roots are equal, giving one root as 0.

this is the code

#include <stdio.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <complex.h>

int main ()
{

float a,b,c,d,root1, root2, real1, real2,imag1,imag2; //define variables

Code:
```cout<<"p(x)= ax^2 + bx + c = 0 " << endl;          //define the equation to be solved

cout<<"    " << endl;

cout<<"enter the 3 parameters a, b, c: " << endl;            //user enters 3 parameters to be calculated
cin >>a>>b>>c;

{
if (a==0)                                  //if a is 0 then this is not a quadratic equation form
cout << "a cannot be 0 in a quadratic equation" << endl;
}

if(a==0){
if (b==0)                  //if a and b are 0 this is not a quadratic equation
cout<< "both a and b cannot be 0 in ax^2 + bx + c =0" << endl;

}

{
d = b*b-4*a*c;
{if (d>0)                        // if d>0 this will give real roots
{
root1= (-b +(sqrt(b*b-4*a*c)))/(2*a);
root2= (-b-(sqrt(b*b-4*a*c))) / (2*a);

cout <<"the first root = " << root1 << endl;       //outputs the first root
cout <<"the second root = " << root2 << endl;         //outputs the second root
}
}
{
if(d<0)                          // if d<0 this will give complex roots

real1= ((-b)/(2*a)) ;
real2= ((-b)/(2*a)) ;
imag1= (((sqrt(b*b-4*a*c))/(2*a))) ;
imag2= (((sqrt(b*b-4*a*c))/(2*a)))  ;

cout <<"the first complex root = " << real1 <<"+ i" << imag1 << endl;       //outputs the first root
cout <<"the second complex root = " << real2 << "- i" << imag2 << endl;         //outputs the second root

}
}

getch();                             // keeps the window open until a key is pressed
return 0;
}```

could anyone help me with this, i'm not very good with c++. thanks

2. > imag1= (((sqrt(b*b-4*a*c))/(2*a))) ;

Here bē-4ac is negative, so you are calculating the square root of a negative number. You need:

imag1= sqrt(-d)/(2*a) ;

(You had already calculated d = b*b-4*a*c, there is no need to repeat that calculation.)

You don't seem to handle the situation when d is equal to 0, that is, when there is only one root, so I don't see how the code could produce bad output (or any output at all).

If you are interested in producing more accurate results please read this:
http://en.wikipedia.org/wiki/Loss_of_significance