So I'm trying to write a simple quadratic solver but it only seems to work some of the time. If I put a as 1, b as -1 and c as -12 I get the two roots -3 and 4, however if I try a as 4, b as -5 and c as -6 i get the roots as 32 and -12 instead of -0.75 and 2. Any thoughts?
This part: ... / 2*a means: divide by 2 and then multiply by a
whereas what is required is divide by (2 multiplied by a)
[Ironically you omitted the parentheses where they were needed, but included them here where they are unnecessary:sqrt((b*b) - (4*a*c))
this would be ok: sqrt(b*b - 4*a*c) ]
Also, the code just about hangs together as the sqrt() function returns a type double, which forces the associated calculation to also use double, but it would be better to use type double rather than int throughout.
Also I'd like to point out that rather than using 'if' again and again, use 'else if' and 'else' as you are checking on the same value. Also keep the discriminant in a variable and check with it. For example: int discr = (b*b)-(4*a*c); then if(discr < 0). Finally, write a function that solves the equation. Make it return a std::pair. It'll save you from writing the formula again and again whenever you solve quadratic equations in your program. For this small program, it won't make much of a difference. However when you write larger programs, it'll make your life a lot easier.
#include <iostream>
#include <cmath>
#include <utility> //Needed for std::pair
usingnamespace std;
pair<float, float> solveQuad(int a, int b, int c)
{
pair<float, float> roots; //The pair which will contain the results.
//It is set to hold two floats.
roots.first = ((-1*b)+sqrt((b*b)-4*a*c))/(2.0*a); //Set the first root
roots.second = ((-1*b)-sqrt((b*b)-4*a*c))/(2.0*a); //Set the second root
return roots;
}
int main()
{
cout << "Solving quadratic in the form ax^2+bx+c" << endl;
cout << "Enter a, b and c: ";
int a, b, c;
cin >> a >> b >> c;
int disc = (b*b)-(4*a*c); //The discriminant
if(disc < 0) //If the discriminant is less than 0
{
cout << "Discriminant < 0. Therefore both roots are imaginary." << endl;
}
elseif(disc == 0) //Use 'else if'. Not 'if' again.
{
cout << "Discriminant = 0. Therefore one repeated root." << endl;
cout << "Result: " << b/2.0;
}
else //If the other conditions fail (i.e if discriminant > 0)
{
//Calculate the roots
pair<float, float> result = solveQuad(a, b, c);
//Output it
cout << "Discriminant > 0. Therefore, two real roots." << endl;
cout << "x1 = " << result.first << "\nx2 = " << result.second << endl;
}
return 0;
}