The Riser
The Riser

Reputation: 329

2nd degree polynomial calculator's output is inconsistent

The following code is supposed to read the 3 coefficients of a 2nd degree equation and output the discriminant and the solutions (if there are any) similar to this online calculator: https://calculator.tutorvista.com/math/496/2nd-degree-equation-calculator.html But for some reason my calculator seems to get some results correctly in some cases but not most of them.

#include <iostream>
#include <math.h>

using namespace std;

int main() {

    float a, b, c;

    cout << "a=" << endl;
    cin >> a;
    cout << "b=" << endl;
    cin >> b;
    cout << "c=" << endl;
    cin >> c;

    float delta = (pow(b, 2)) - (4 * a*c);
    float summit = (-b) / (2 * a);
    float x1 = (-(b) + (sqrt(delta)) / (2 * a));
    float x2 = (-(b) - (sqrt(delta)) / (2 *a));



    cout <<"Discriminant="<< delta << endl;

    if (delta < 0) {
        cout << "No solution" << endl;
    }
    else if (delta == 0) {
        cout << "Unique solution is:" << summit << endl;

    }
    else {
        cout << "First solution is:" << x1 << endl;
        cout << "Second solution is:" << x2 << endl;

    }
    std::cin.ignore();
    std::cin.get();
}

Here are some rare input examples where my calculator works as intended,according to the online calculator linked above:

a=3;b=1;c=24;

a=1;b=0;c=0;

a=1;b=-4;c=4;

But things don't always go so smoothly,for example inputting 1;4;-12 gives you 8 and 0 as opposed to 6 and -2 (notice how the results are off by 2),in other cases one of the solutions would be correct while the other won't,and most of the time the reults are completely off.

I'm not exactly sure if the problem is from the discriminant or the solution,because sometimes the former would be correct while the latter isn't.

Is there a certain etiquette when it comes to writing mathematical formulas in C++ that I'm not aware of?

Thanks in advance.

Upvotes: 0

Views: 213

Answers (1)

Andrew Kashpur
Andrew Kashpur

Reputation: 746

formula is ( -b +- sqrt(D) ) / 2a ,

but you calculate -b +- sqrt(D) / 2a,

because division takes precedence over addition/substruction, so your lines

float x1 = (-(b) + (sqrt(delta)) / (2 * a) );
float x2 = (-(b) - (sqrt(delta)) / (2 * a) );

should be

float x1 = (-(b) + sqrt(delta)) / (2 * a);
float x2 = (-(b) - sqrt(delta)) / (2 * a);

Upvotes: 5

Related Questions