I don't know what doesn't work with my c++ equation's type of root test: It doesn't d

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AntoniaMouawad
    New Member
    • Sep 2013
    • 1

    I don't know what doesn't work with my c++ equation's type of root test: It doesn't d

    Code:
    #include <iostream> 
    #include <cmath>
    using namespace std;
    int 
    main (int argc, char** argv)
    {
    	double a=0.0;
    	double b=0.0;
    	double c=0.0;
    	double num=0.0;
    
    	cout <<"Given this form of equation: aX2 + bX + c = 0"<<endl;
    	cout <<"Input the value of a (the coefficient of X2)"<<endl;
    	cin>>a;
    	cout <<"Input the value of b (the coefficient of X)"<<endl;
    	cin>>b;
    	cout <<"Input the value of c (the constant value)"<<endl;
    	cin>>c;
    	cout<<"Your equation is the following"<<endl;
    	cout<<a<<"X2 + "<<b<<"X + "<<c<<" = 0"<<endl;
    	num= pow(b,2)-(4*a*c);
    	if (num=0)
    	{
    		cout<<"This equation has a single (repeated) root."<<endl;
    	}
    	if (num<0)
    	{
    		cout<<"This equation has two complex roots."<<endl;
    	}
    	if (num>0)
    	{
    		cout<<"This equation has two real roots."<<endl;
    	}
    	return 0;
    }
    Last edited by Banfa; Sep 20 '13, 01:27 PM. Reason: Please use code tags, [code] [/code] round your code in future
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Your first problem is that at line 22 you have a single = which is assignment and not a comparison ==.

    This sets num to 0 which causes all the if statements to return false.

    However correcting your comparison is unlikely to completely fix the problem because doubles hold only approximations to numbers and generally we say that you should never use == or != to compare a double value, == will always return false and != will always return true.

    That said you code does appear to work in some cases for example a=1, b=2, c=1 but I would expect there to be cases where it fails to correctly determine that a given equation has a single (repeated) root, although I haven't found an actual case yet.


    EDIT:

    I have an example for the equation

    X2 + 0.387368 X + 0.037513491856

    Your program outputs "This equation has two complex roots." where it should output "This equation has a single (repeated) root." because that equation has a root at -0.193684.

    This is due to rounding errors produce in the approximation of the numbers when stored as doubles.
    Last edited by Banfa; Sep 20 '13, 01:48 PM. Reason: Added example

    Comment

    Working...