Help with quadratic equation solver

Was wondering why this bit won't compile. I get the errors in the line
r1 = ((-B) + sqrt(B^2 - 4*A*C)/(2*A); .
before, when types A, B, C, r1 and r2 were ints, it would compile but all answers would be -2147... then when I tried changing the types to float and then double is when it stopped even compiling.

1
2
3
4
5
6
7
8
9
10
11
            cout << "This tool solves quadratics ONLY in the form of: \n\tAx^2 + Bx + C" << endl;
            cout << "Please enter the 'A' in your problem: " << endl;
            cin >> A;
            cout << "Please enter the 'B': " << endl;
            cin >> B;
            cout << "Please enter the 'C': " << endl;
            cin >> C;
            
            r1 = ((-B) + sqrt(B^2 - 4*A*C)/(2*A);
            r2 = ((-B) - sqrt(B^2 - 4*A*C) / (2*A);
            cout << "The first result is " << r1 << endl;
btw, I have included <cmath>, if that was unclear
Count the number of right-opening parenthesis and left-opening parenthesis in your r1 and r2 assignment lines. Are they equal?
@Ispil-Thanks, that helped to compile, but now all my answers are "-1.#IND and -1.#IND."
BTW updated code to
1
2
3
4
5
6
7
8
9
10
11
 cout << "NOTE: this tool solves quadratics ONLY in the form of: \n\tAx^2 + Bx + C" << endl;
            cout << "Please enter the 'A' in your problem: " << endl;
            cin >> A;
            cout << "Please enter the 'B': " << endl;
            cin >> B;
            cout << "Please enter the 'C': " << endl;
            cin >> C;
            
            r1 = ((-B) + sqrt(pow(B,2) - 4*A*C)/(2*A));
            r2 = ((-B) - sqrt(pow(B,2) - 4*A*C) / (2*A));
            cout << "The results are: " << r1 <<" and " << r2 << endl; 
.

All variables are doubles. Any tips?
EDIT: Fixed completely, thanks :)
Last edited on
I don't know what numbers you used to test it with, but I see three problems right away:

By the PEMDAS order (which the compiler will also follow), the sqrt() result will be divided by 2*A and then -B is added to it.

In C++, B^2 is not the same as B*B. The ^ operator is a bitwise operator called XOR. For squaring B, either use B*B or pow(B,2).

Also, what happens when 4*A*C > B*B? How will you program react to the square root of a negative number? Have some way to handle complex solutions.
I know in quadratic formulas, there is a possibility of "imaginary numbers". If I were you, I would check to see if (B * B) - 4 * A * C is >= 0, and if it isn't, then make it positive after the calculation then add an "i" at the end indicating imaginary number.
Topic archived. No new replies allowed.