sqrt Function Will Not Compile

I am writing a program to compute the standard deviation of four numbers in the function description for the function "deviation", I make a function call to the square root function. However my compiler will not accept this. It says that sort is an "undeclared identifier".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  #include <iostream>
double deviation(double first, double second, double third, double fourth);
double average(double first, double second, double third, double fourth);
double average2(double first, double second, double third, double fourth);
using namespace std;
int main()
{
    double first = 1.0, second = 2.0, third = 3.0, fourth = 4.0;
    return 0;
}

double deviation(double first, double second, double third, double fourth)
{
    return sqrt(average2(first, second, third, fourth));
}

double average(double first, double second, double third, double fourth)
{
    return (first + second + third + fourth) / 4;
}

double average2(double first, double second, double third, double fourth)
{
    return (first -  average(first, second, third, fourth)) + (second -  average(first, second, third, fourth)) + (third -  average(first, second, third, fourth)) + (fourth -  average(first, second, third, fourth));
}
You need to #include <cmath> in order to use sqrt.
Last edited on
You also need to link with the C math library (libm). For example, using GCC:

    g++ foo.cpp -lm

Hope this helps.
@Duoas
I thought libm was automatically linked in for C++ programs? (I once heard somewhere that libstdc++ references functions in libm, so you automatically get libm every time)
You could be right.

/me googles

Yep. It looks like the GCC will do that for you.

http://osdir.com/ml/linux.gcc/2005-01/msg00016.html

IDK about other compilers.
Topic archived. No new replies allowed.