Hello, my professor is wanting us to make a program that calculatates the quadratic equation. However he want it to be able to calculate imaginary roots. I have tried googling it but have not found any answers. Here is my code so far. Please help :)
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
/*
----------------------------------------------------
This program is by Brandon Cavendish. 9/7/2017
It will find the real roots for a quadratic equation
if > 0
If == 0 (repeated)
if < 0
x1, x2 = -b+-sqrt(b^2-4ac)/2a
----------------------------------------------------
*/
// declaring variables.
double a = 0.0;
double b = 0.0;
double c = 0.0;
double x1 = 0.0;
double x2 = 0.0;
Did you delete a post with this same code in it? Regardless:
1 2 3 4 5 6 7 8 9
#include<complex>
c++ supports a complex type.
I haven't used it in a while, I think this is right.
complex<double> x;
x.real = -23;
x = sqrt(x);
cout << x.imag << endl;
cout << x << endl; //I think this prints something + other i format
you make your own complex type or wing it with a bunch of stray variables, but the language will do it for you if you don't have a requirement to do it the hard way.
Brandon, please try not to double (actually, triple) post - it confuses threads. Also, please put your code within code tags.
You have a couple of choices (at least):
(1) Make both roots and coefficients complex<double> and the sqrt problem magically goes away.
This is probably only worth doing if your coefficients are themselves complex. You don't say whether this is the case, but I would guess not.
(2) Work out realPart and imagPart separately and simply write them out with cout as
realPart + imagPart *i
You only have to do this in the case of the discriminant being negative.
To take an example:
4+sqrt(-9) becomes 4+sqrt(+9).i
where I have written i for the square root of (-1); (electrical engineers often use j instead of i).
If you don't want i in your output then could also write them as the ordered pair (4,3).
It goes without saying that you should know how to handle complex numbers mathematically first.
hey, @lastchance, it's no bigly thing and it isn't meant to be a punitive exercise against OP but where this duplication is known it's a good idea to post the 'circular' reference.
We've all read the excuses and, probably, not knowing happens more often than not but as we all know duplication of effort gives everybody the shits.
Thanks, Kemort. I would have posted references to all three threads, but I'm trying to type on an iPad on the way to work and it's useless for handling long weblinks!