Right, got it.
There's two problems here.
Lets address this first: the quadratic formula in your code is off. Remember, the whole equation is over 2a and, from the looks of the brackets there, I'd say that isn't happening. Precedence can be ugly in C++, so sometimes it's good to split things up. Here's how I did the quadratic equation.
1 2
|
x1 = (-b + (sqrt((b*b) - (4*a*c))));
x1 = x1 / (2*a);
|
For me, it makes things a little clearer and makes sure I'm getting what I want.
Secondly, is your roots issue. Basically, if there's no real roots, then there's no point doing the equation. So, you may want to check for real roots before even thinking about getting into the meatier stuff.
1 2 3 4
|
// Declare variables
// Get inputs from user
// Check roots before solving
// Solve equation if needed
|
So, in the above, I created another double called discriminant and set that to the sum of b^2 - 4ac. We know that if the discriminant is less than zero, there's no real roots, so once I had the discriminant, I just added a check.
1 2 3 4 5 6 7 8 9 10 11
|
if (discriminant < 0)
{
cout << "Equation has no real roots" << endl;
return 0;
}
else
{
// Perform calculations here
// Output answers
return 0;
}
|
Hope this helps.