program for real roots of quadratic equation

This is a discussion on program for real roots of quadratic equation within the C++ Programming forums, part of the General Programming Boards category; Hi I'm trying to write a simple console program to find the real roots of a quadratic equation. It's part ...

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    254

    program for real roots of quadratic equation

    Hi

    I'm trying to write a simple console program to find the real roots of a quadratic equation. It's part of self-study. I have a rough idea which you can have a look on below. Please help me to finish it and correct the errors. I'm highly grateful for your guidance and help. Thanks a lot.

    I hope this general pseudocode is correct:

    Code:
    Read the coefficients “a” and “b”, and constant “c” of ax^2 + bx + c = 0
    Let Discriminant D = b^2 - 4ac
       IF D >= 0 THEN
            Real root R1 = (-b + sqrt(D))/(2a)
            Real root R2 = (-b - sqrt(D))/(2a)
       ELSE
            Print “no real solutions”
       ENDIF
       Print R1 and R2
    Stop
    Here is my 'rough' and full of errors incomplete implementation:
    Code:
    #include <iostream>
    using namespace std;
    int main ()
    {
            float a, b, c, R1, R2 //variables and constants used;
            cout<< "Enter a, b, c of the equation ax^2+bx+c==0=";
            cout<< "Enter a=";
            cin>> a;
            cout<< "Enter b=";
            cin>> b;
            cout<< "Enter c="
            cin>> c;
            D = b^2 - 4ac;
            if (D>=0)
               {
               R1 = (-b + sqrt(D))/(2a)
               R2 = (-b - sqrt(D))/(2a)
                  else
                    no real roots exist
                }
    I'm an outright beginner. Using Win XP Pro and Code::Blocks. Be nice to me, please.

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    2,521
    instead of
    Code:
    R1 = (-b + sqrt(D))/(2a)
    try
    Code:
    R1 = (-b + sqrt(D))/(2 * a)
    Edit: D = b^2 - 4ac; is wrong look up the pow/power function from math.h
    http://www.cplusplus.com/reference/clibrary/cmath/
    Last edited by stahta01; 03-31-2011 at 05:14 PM.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    254
    Quote Originally Posted by stahta01 View Post
    instead of
    Code:
    R1 = (-b + sqrt(D))/(2a)
    try
    Code:
    R1 = (-b + sqrt(D))/(2 * a)
    Edit: D = b^2 - 4ac; is wrong look up the pow/power function from math.h
    cmath (math.h) - C++ Reference
    Hi stahta01

    Thanks for the reply. Do you mean I have to include header file "#include math.h"? I was told the header files with ".h" extensions are outdated.

    On the webpage you referred me to I found this:

    Code:
    /* pow example */
    #include <stdio.h>
    #include <math.h>
    
    int main ()
    {
      printf ("7 ^ 3 = %lf\n", pow (7,3));
      printf ("4.73 ^ 12 = %lf\n", pow (4.73,12));
      printf ("32.01 ^ 1.54 = %lf\n", pow (32.01,1.54));
      return 0;
    }
    I don't understand the bold parts. And could you please complete that code in my first post?

    Regards
    Jackson
    I'm an outright beginner. Using Win XP Pro and Code::Blocks. Be nice to me, please.

  4. #4
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,236
    Why the heck would you use pow() to implement the squaring of a number? Just multiply it with itself and be done with it.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  5. #5
    C++ Junkie Mozza314's Avatar
    Join Date
    Jan 2011
    Location
    Australia
    Posts
    174
    Quote Originally Posted by jackson6612 View Post
    Hi stahta01

    Thanks for the reply. Do you mean I have to include header file "#include math.h"? I was told the header files with ".h" extensions are outdated.

    On the webpage you referred me to I found this:

    Code:
    /* pow example */
    #include <stdio.h>
    #include <math.h>
    
    int main ()
    {
      printf ("7 ^ 3 = %lf\n", pow (7,3));
      printf ("4.73 ^ 12 = %lf\n", pow (4.73,12));
      printf ("32.01 ^ 1.54 = %lf\n", pow (32.01,1.54));
      return 0;
    }
    I don't understand the bold parts. And could you please complete that code in my first post?

    Regards
    Jackson
    Never mind the printf nonsense, just use std::cout like is in the code you posted before (although printf is good background knowledge, you should avoid it in C++).

    For standard headers, instead of #include <abc.h>, in C++, you write #include <cabc>. So use #include <cmath> to use std::sqrt.

    Also, Brewbuck is right about using pow being silly here, to do b^2, just write b * b.

    Aside from that you're missing several semicolons, "else" should occur after the closing brace for the "if", and while you're at it you should fix up your indentation a bit so it looks more like this (I've deliberately only adjusted indentation without fixing other problems here):

    Code:
    #include <iostream>
    using namespace std;
    int main ()
    {
        float a, b, c, R1, R2 //variables and constants used;
        cout<< "Enter a, b, c of the equation ax^2+bx+c==0=";
        cout<< "Enter a=";
        cin>> a;
        cout<< "Enter b=";
        cin>> b;
        cout<< "Enter c="
        cin>> c;
        D = b^2 - 4ac;
        if (D>=0)
        {
            R1 = (-b + sqrt(D))/(2a)
            R2 = (-b - sqrt(D))/(2a)
            else
                no real roots exist
        }
    Last edited by Mozza314; 03-31-2011 at 07:18 PM.

  6. #6
    Programming King Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Middle of NoWhere
    Posts
    320
    D is declared no where.
    I don't care if someone doesn't like me, i was not put on earth to entertain everyone.

    No King, no Queen, I am the ACE of battle.

  7. #7
    Registered User
    Join Date
    Mar 2011
    Posts
    254
    Thanks everyone. Below is the improved code. I humbly request you to correct mistakes and let me have a running program ans ask some questions related to it. Thanks.

    Code:
    #include <iostream>
    # include <cmath>
    using namespace std;
    int main ()
    
    {
        clrscr()
        float a, b, c, R1, R2 //variables and constants used;
        cout<< "Enter a, b, c of the equation ax^2+bx+c==0=";
        cout<< "Enter a=";
        cin>> a;
        cout<< "Enter b=";
        cin>> b;
        cout<< "Enter c=";
        cin>> c;
        float D = b*b - 4ac;
        if (D>=0)
        {
            cout<< "R1 is="  (-b + sqrt(D))/(2*a);
            cout<< "R2 = (-b - sqrt(D))/(2*a);
         }
          else
          cout<< "no real roots exist"<<endl;
          getch()
    }
    I'm an outright beginner. Using Win XP Pro and Code::Blocks. Be nice to me, please.

  8. #8
    C++ Junkie Mozza314's Avatar
    Join Date
    Jan 2011
    Location
    Australia
    Posts
    174
    clrscr() is not standard, it should be avoided.

    A semicolon is still missing here:
    Code:
        float a, b, c, R1, R2; //variables and constants used;
    and another one here:
    Code:
          getch();
    I don't know what that getch() is doing there (are you running the program by double-clicking a .exe file on windows, and want to stop the screen from closing after the calculation?), I think that's a C function, use cin.get() if you must.

    You're also missing * between 4, a, c on this line:
    Code:
        float D = b*b - 4*a*c;
    And you're missing a "<<" on this line:
    Code:
            cout<< "R1 is=" << (-b + sqrt(D))/(2*a);
    Now a couple of style points:

    Mainly, indentation, when using spaces instead of tabs (which I recommend), choose a set number of spaces to use for each indentation level, and stick with it (I recommend sets of 4 spaces, which it appears you are mostly using). The lines in red are indented incorrectly:

    Code:
        if (D>=0)
        {
            cout<< "R1 is="  (-b + sqrt(D))/(2*a);
            cout<< "R2 = (-b - sqrt(D))/(2*a);
         }
          else
          cout<< "no real roots exist"<<endl;
          getch()
    Also with this code, I don't have a problem with omitting the braces for single statements in if/else blocks, but if any block in the if/else sequence requires braces, I say they should all have braces:
    Code:
        if (D>=0)
        {
            cout<< "R1 is="  (-b + sqrt(D))/(2*a);
            cout<< "R2 = (-b - sqrt(D))/(2*a);
         }
          else
          {
          cout<< "no real roots exist"<<endl;
          }
          getch()
    I think this looks ugly:

    Code:
        cout<< "Enter b=";
        cin>> b;
    I would put spaces on both sides of "<<" and ">>":
    Code:
        cout << "Enter b=";
        cin >> b;
    In fact I would do that for arithmetic operators as well, but that's getting down to my personal taste:
    Code:
        float D = b*b - 4*a*c; // bad
        float D = b * b - 4 * a * c; // good
    Last edited by Mozza314; 03-31-2011 at 11:09 PM.

  9. #9
    Registered User
    Join Date
    Mar 2011
    Posts
    254
    Mozza314: I genuinely thank you for all you help and guidance. It is really kind of you. I would stick to your advice on the style from this point onward.

    I do still have a couple of questions to ask about the above code which I would ask soon. But here is a BIG question:

    When I have entered the values of "a", "b" and "c" it simply closes. It doesn't even display "R1" and "R2". What can I do to stop this and make this program functional? Please help me. I'm using Dev-C++. Thanks.

    Code:
    #include <iostream>
    # include <cmath>
    #include <stdlib.h>
    
    using namespace std;
    int main ()
    
    {
        float a, b, c, R1, R2; //variables and constants used
        cout << "Enter a, b, c of the equation ax^2 + bx + c = 0" << endl;
        cout << "Enter a = ";
        cin >> a;
        cout << "Enter b = ";
        cin >> b;
        cout << "Enter c = ";
        cin >> c;
        float D = b*b - 4*a*c;
        if (D >= 0)
        {
            cout << "R1 is = " << ( -b + sqrt(D) )/( 2*a );
            cout << "R2 is = " << ( -b - sqrt(D) )/( 2*a );
        }
        else
        {
        cout << "no real roots exist" << endl;
        }
        return 0;
    }
    Last edited by jackson6612; 04-01-2011 at 12:23 PM. Reason: encountered a major setback!
    I'm an outright beginner. Using Win XP Pro and Code::Blocks. Be nice to me, please.

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    6,208
    The concern is not that the program does not display the output. It is that the program terminates, and the operating system - in its quest to be helpful and clean things up - closes the window showing the output before you can see it.

    The conventional way to stop the program from terminating immediately is to add additional code at the end of main (before the return 0) that waits for additional user input. There are many opinions on the "right" way to do this that I won't buy into, but one way is;
    Code:
       std::cin.ignore ( std::numeric_limits<streamsize>::max(), '\n' );
       std::cin.get();
    (assuming <limits> has been #include'd).
    Right 98% of the time, and don't care about the other 3%.

  11. #11
    C++ Junkie Mozza314's Avatar
    Join Date
    Jan 2011
    Location
    Australia
    Posts
    174
    Quote Originally Posted by jackson6612 View Post
    Mozza314: I genuinely thank you for all you help and guidance. It is really kind of you. I would stick to your advice on the style from this point onward.

    I do still have a couple of questions to ask about the above code which I would ask soon. But here is a BIG question:

    When I have entered the values of "a", "b" and "c" it simply closes. It doesn't even display "R1" and "R2". What can I do to stop this and make this program functional? Please help me. I'm using Dev-C++. Thanks.
    You're welcome. I agree with grumpy's answer to your question.

  12. #12
    Registered User
    Join Date
    Mar 2011
    Posts
    254
    I used "system("PAUSE")" at the end and it doesn't close now.

    Code:
    #include <iostream>
    # include <cmath>
    #include <stdlib.h>
    
    using namespace std;
    int main ()
    
    {
        float a, b, c, R1, R2; //variables and constants used
        cout << "Enter a, b, c of the equation ax^2 + bx + c = 0" << endl;
        cout << "Enter a = ";
        cin >> a;
        cout << "Enter b = ";
        cin >> b;
        cout << "Enter c = ";
        cin >> c;
        float D = b*b - 4*a*c;
        if (D >= 0)
        {
            cout << "R1 is = " << ( -b + sqrt(D) )/( 2*a ) << endl;
            cout << "R2 is = " << ( -b - sqrt(D) )/( 2*a ) << endl;
        }
        else
        {
        cout << "no real roots exist" << endl;
        }
        
        system("PAUSE");
    }
    I'm an outright beginner. Using Win XP Pro and Code::Blocks. Be nice to me, please.

  13. #13
    C++ Junkie Mozza314's Avatar
    Join Date
    Jan 2011
    Location
    Australia
    Posts
    174
    But now your code is non-standard. system("PAUSE") is windows specific.

  14. #14
    Registered User
    Join Date
    Apr 2008
    Posts
    90
    Seeing as the problem being addressed is Windows specific, it's probably a fair tradeoff.

  15. #15
    C++ Junkie Mozza314's Avatar
    Join Date
    Jan 2011
    Location
    Australia
    Posts
    174
    Quote Originally Posted by Clairvoyant1332 View Post
    Seeing as the problem being addressed is Windows specific, it's probably a fair tradeoff.
    What problem is windows specific? I don't see how finding the roots of a quadratic equation is windows specific.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 09-16-2009, 06:00 AM
  2. Replies: 4
    Last Post: 08-18-2009, 03:32 PM
  3. Cubic equation program not giving me right answers
    By face_master in forum C++ Programming
    Replies: 8
    Last Post: 08-24-2006, 05:42 PM
  4. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21