Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ code not compiling correctly

  1. Jun 3, 2008 #1
    I'm pretty sure I wrote the correct code for the quadratic formula and yet Dev-C++ continues to find a problem with my code. I will post the code I've written:


    int main()
    double root1,root2,a,b,c,root;

    cout << "Enter the coefficients a,b,c: "; ! This is the line where Dev-C++ finds an error
    cin >> a >> b >> c;
    cout << "The solutions are " <<root1 << " and " <<root2 << "\n";


  2. jcsd
  3. Jun 3, 2008 #2


    User Avatar
    Science Advisor
    Homework Helper

    You need either std::cout or put a "using namespace std" declaration at the top.
  4. Jun 3, 2008 #3
  5. Jun 4, 2008 #4
    As others have pointed out, there are a couple of mistakes. First, functions such as cout, cin, and so on belong to the standard namespace in C++. So if you want to use them in your code you need to do one of two things. The first option is to precede every call to these functions with a declaration that they're from the standard namespace, i.e., instead of

    Code (Text):
    cout << "This is some text..." << endl;
    you should have

    Code (Text):
    std::cout << "This is some text..." << std::endl;
    However, typing std:: each time you call a function from the C++ standard library is cumbersome. Therefore, you can save time by using the following as a preprocessor directive in your code:

    Code (Text):
    using namespace std;
    Typically, you should declare all of the parts of the standard library that your code needs and then include "using namespace std;" on the next line.

    The other difficulty is that you should use the cmath library instead of the math library. Both are essentially identical apart from the fact that cmath allows its members to be placed in the standard namespace. So your code should really look like this:

    Code (Text):
    #include <iostream>
    #include <cmath>

    int main()
      double root1, root2, a, b, c, root;

      cout << "Enter the coefficients a, b, c: " << endl;
      cin  >> a >> b >> c;

      root = sqrt (b*b - 4.0*a*c);
      root1 =   .5*(root - b) / a;
      root2 =   -.5*(root - b) / a;
      cout << "The solutions are:" << endl
           << "root1 = " << root1  << endl
           << "root2 = " << root2
           << endl;

      return 0;
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: C++ code not compiling correctly