Quadratic Equation solver program returning incorrect answers

I programmed a quadratic equation solver, but if a is not equal to 1, it gives incorrect answers. For example, if a=1, b=10, and c=25, then it returns x= -5 and x= -5, which is correct. But if a=5, b=6, and c=1, it returns x= -5 and x= -25, which is incorrect; it should be x= -1 and x= -0.2. What am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string exit = "y";
    cout << "Welcome to the quadratic equation solver!\nThis accepts equations of the form ax^2 + bx + c = 0.\n";
    float a, b, c, s1, s2;
    while (exit == "y")
    {
    cout << "Please enter value for a: ";
    cin >> a;
    cout << "Please enter value for b: ";
    cin >> b;
    cout << "Please enter value for c: ";
    cin >> c;
    cout << "The equation you entered is " << a << "x^2 + " << b << "x + " << c << " = 0.\n";
    s1 = (-b + sqrt (b*b - 4*a*c)) / 2*a;
    s2 = (-b - sqrt (b*b - 4*a*c)) / 2*a;
    if (b*b - 4*a*c < 0)
        cout << "Cannot be solved with real numbers.\n";
    else
        cout << "The solutions are x = " << s1 << " and x = " << s2 << ".\n";
    cout << "Push Y to continue, or any other key to exit."; cin >> exit;
    }
    return 0;
}
This / 2*a; means divide by 2, then multiply by a.
What you want is to do the multiplication first, / (2*a);

One other comment, ideally you would test (b*b - 4*a*c) >= 0 before attempting to calculate the square root, not afterwards.
Oh, I see. I haven't really memorized how a lot of C++ works yet so I would have never figured that out on my own.
Topic archived. No new replies allowed.