### Quadratic Equation & imaginary numbers

I have been looking for about a week now and I cant seem to find exactly what i am looking for. I am writing a program for the dreaded Quadratic Equation. it works fine until I get to an equation that involves the negative discriminant and with that, the solution involves an imaginary number. I know that the complex library is out there but I am not sure if that will do what I want. Is there a way to solve for the imaginary number?

Suppose that I have an equation where the a, b & c value are 3, 2, 1 respectively. With those numbers, the solution is I think:

x= -2 +- 2i sqrt2/ 6. It can also be rediced, i think but at this moment that is beside the point.

What would I use to get this solution? or should I stop once I get a discriminant value of <0?

I dont have my code but it works fine until i get a negative descriminant (NaN)
you need to cover that case on your own. the math library can't solve sqrt(-1).
just use an if statement for that case and then continue with the math.
So all i can do about that is print that solution out to the screen?

cout << "x = " << variable << "=- " variable << "i" << variable.....etc?

Is there a square root symbol?
 I know that the complex library is out there but I am not sure if that will do what I want

It's been part of C++ from the very beginning, it's older than std::cout. Of course it will do what you want.

 ``1234567891011121314`` ``````#include #include int main() { std::complex a = 3.0; std::complex b = 2.0; std::complex c = 1.0; std::complex d = sqrt(pow(b,2)- 4.0*a*c); std::cout << "The answers are " << (-b + d)/(2.0*a) << " and " << (-b - d)/(2.0*a) << '\n'; }``````

online demo: http://ideone.com/Ri4dr5

Awesome, thanks. I can work with that!
Ok. One more question. If I understand the results, one part of the answer is the real and one part is the imaginary number. How do I access each part? imag() & real() doesn't seem to do it. I would like to get an answer with an "i".
What's wrong with imag() and real() ?

 ``12345678910111213141516`` ``````#include #include int main() { std::complex a = 3.0; std::complex b = 2.0; std::complex c = 1.0; std::complex d = sqrt(pow(b,2)- 4.0*a*c); std::complex r1 = (-b + d)/(2.0*a); std::complex r2 = (-b - d)/(2.0*a); std::cout << "The answers are " << std::showpos << '\n' << r1.real() << " " << r1.imag() << "i\n" << r2.real() << " " << r2.imag() << "i\n"; }``````

online demo: http://ideone.com/saP2Og
I've been messing with it for an hour and you guys get it in like 5 minutes. I hope I get good enough to help other like ya'll are helping me. I will fix it tomorrow. Right now "moonshiners" is on! Thanks again!
Topic archived. No new replies allowed.