I am having problems using the square root function in my program. I have included <cmath> outside of main and my formula using the square root looks like this:

area=sqrt(s*(s-a)*(s-b)*(s-c));

but, I keep getting an error that says 'sqrt' cannot be used as a function. I would appreciate any suggestions. Thank you.

Are variable a, b, c, s all integer types?

What is the exact error message?

sqrt( ) requires an argument that is a floating point type. Typecasting will be needed if your args are all integer types.

If you include <cmath> sqrt function lives in std namespace. So declare using namespace std; or (better) use std::sqrt(...) or declare using std::sqrt; .
Probably, that's all your troubles now...

I don't think that <cmath> is in std namespace:
Example with iostream (using namespace std;)

Example with cmath (doesn't have using...)


Maybe he declared another function named sqrt? Or a variable perhaps.

You are right that the functions in cmath aren't in std namespace -- they are in global namespace. The version of cmath supplied with vc++ 2008 express has all the using statements at the bottom of the file.

>>area=sqrt(s*(s-a)*(s-b)*(s-c));
I get no errors/warnings when I declare each of the variables float. So there must be something else wrong with the program.

With DEVCPP this works just fine:

// obtain square root

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
   double s, a, b, c, area;

   s = 5.0;
   a = b = c = 1.5; 
   area = sqrt(s*(s-a)*(s-b)*(s-c));
   
   cout << "sqrt(" << s*(s-a)*(s-b)*(s-c) << ") = " << area << '\n';

   cin.get(); // wait
   return EXIT_SUCCESS;
}

Maybe there's a macro defined with a name of "sqrt" ? There are macros in the Windows.h header such as "min" and "max" which conflict with std::numeric_limits<anything>::min()/max();

In which case for the Windows.h header you will want to define: NOMINMAX
to remove the macro.

]use this code

#include<iostream>
#include
using namespace std;

int main(int argc, char *argv[])
{
double s, a, b, c, area;

s = 5.0;
a = b = c = 1.5;
area = sqrt(s*(s-a)*(s-b)*(s-c));

cout << "sqrt(" << s*(s-a)*(s-b)*(s-c) << ") = " << area << '\n';

cin.get(); // wait
return EXIT_SUCCESS;
}

This article has been dead for over six months. Start a new discussion instead.