Getting different result with same number

I'm using the trial and error method to attempt to find the sqrt of b^2-4ac. I enter the numbers 5,1,1, to attempt to trigger the two real roots option. This part is successful. When it shows the root value though i receive different numbers every time, including 0,inf, and random small numbers that are approaching zero. I have no idea what this means and I would like to know what error would result in that.


#include <iostream>
#include <cmath>
using namespace std;

int main()
{
double b;
double a;
double c;
double root;
root = (b*b-4*a*c);

cout << "enter b of the discriminant";
cin >> b;
cout << "enter a of the discriminant";
cin >> a;
cout << "enter c of the discriminant";
cin >> c;

if (b*b-4*a*c == 0)
{
cout << "Single repeated root";
}
else if (b*b-4*a*c < 0)
{
cout << "Two complex roots";
cout << root <<", -"<<root;
}
else if (b*b-4*a*c > 0)
{
cout << "Two real roots";
cout << root;
}
else
{
cout << "Check your input";
}
return 0;
}
root = (b*b-4*a*c); at line 11 in your program is not doing anything useful. At that stage in the program, none of a, b and c have been assigned any particular values - they contain garbage.

You need to move that calculation further down so it is done after the user has entered the values.
I see. Thanks.
Topic archived. No new replies allowed.