1. Discriminant logic
The solution to a quadratic equation becomes complex once the
discriminant is less than zero.
The discriminant is
b*b - 4*a*c, not
sqrt(b*b - 4*a*c). The discriminant is what needs to be checked to see if it's below zero, not the square root of the discriminant; the point is preventing the operation of sqrt on a negative number in the first place.
2. Order of operations
x1 = (-b + (sqrt ((b*b) -4*a*c))) /2*a;
This is slightly wrong. When you do
something/2*a, you are dividing something by 2, and then
multiplying the result by a. Use parentheses:
x1 = (-b + (sqrt ((b*b) -4*a*c))) /(2*a);
3. If-else logic with comparisons
Doing
if ( A > 0) { ... } else if (A < 0) { ... }
is not only redundant, but does not account for when A == 0.
Simplify and correct your logic to:
1 2 3 4 5 6
|
if (b*b -4*a*c >= 0) {
findX (a,b,c);
}
else {
findCompX(a, b, c);
}
|
4. Complex arithmetic
Once you know you're in the complex plane, you need to divide up the logic into its real and imaginary parts. Multiplying the discriminant by -1 if the discriminant less than zero is okay, but you need to follow that up with a modified form of the full formula.
for n < 0,
sqrt(n) = i * sqrt(-n).
You still need to apply the full formula, BUT you now need to split it into its real and imaginary components.
The real part will be
-b / (2a) for both roots, because sqrt(negative) is purely imaginary.
The imaginary part will be (plus or minus)
sqrt(-discriminant) / (2a).
print it like this
1 2 3 4 5
|
double x_real = // ...
double x_imaginary = // ...
cout << "There are two complex solutions: " <<
x_real << " + " << x_imaginary << "i and " <<
x_real << " - " << x_imaginary << "i" << endl;
|
5. You're mixing floats with doubles (last and least)
Either one is fine for your purposes (you're not doing high-precision scientific computing), but stick with one. I would suggest double simply because that is the default type when you write 0.0 in C++. Use floats if you need to interact with another library/API (such as OpenGL) that needs input as floats.