dealing with some logic errors

Hello peeps! I'm having some problems with my codes. I had done a quadratic equation calculator programm. The problems were some of the number that I key in will result in appearing "nan" and also the other one would be no output printed at all. I hope that anybody can explain to me about how to deal with this kind of logic error.

[code]
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
double x1,x2,x3,x4,x5,x6,sum1;
int a,b,c;
cout << " ax^2+bx+c " << endl;
cout << " please enter the value of a,b,c : ";
cin >> a >> b >> c;

if(a==0){cout << " undefined. " << endl;}
else{sum1 = (b*b)-(4*a*c);}
x1 = ((-b+sqrt(sum1))/(2*a))*1.0;
x2 = ((-b-sqrt(sum1))/(2*a))*1.0;
if(sum1<0){
cout << " there will be two complex roots. " << endl;
cout << " the roots are " << x1 << " , " << x2 << endl;
}
else if(sum1=0){
cout << " there will be equal roots. " << endl;
cout << " the roots are " << x1 << " , " << x2 << endl;
}
else if(sum1>0){
cout << " the will be two real roots. " << endl;
cout << " the roots are " << x1 << " , " << x2 << endl;
}
return 0;
}

Please use code tags - it will make it much easier for people to read your code and help you.

There are a number of issues with your code - and these are noted without actually compiling and running.

If a == 0 you correctly point out that the result is undefined (because the equation won't actually be quadratic); however, you then keep going anyway, and so you will fail because of dividing by 0 when you try to calculate x1 and x2.

If sum1 < 0 then you will find that taking its square root is not a clever idea (actually, it will automatically crash) - one way or another you will have to work with complex numbers at this point.

Your condition (sum1 = 0) doesn't do what you think it does: single = means assignment (i.e. giving a value); logical comparison requires ==.


There are other issues. Making a, b, c integers is possible, but rather restrictive.
The *1.0 in the formulae for x1 and x2 is pointless: sum1 is double, so the result of the previous bracketed calculation will be double. sum1 isn't a sensible name: it clearly isn't a sum: most people call it a discriminant (because it discriminates between the possible types of outcome).


I suggest that you modify your code in line with some or all of these suggestions and repost with code tags. Give examples of the cases which fail.
Last edited on
Topic archived. No new replies allowed.