Search code examples
visual-studio-2010cmath

#include <cmath>


What is wrong with the code snippet below that VS2010 wouldn't compile it?

int m = sqrt( n );

( I am trying to ascertain whether an integer is prime... )


Solution

  • You need to pass a specific floating point type to sqrt - there's no integer overload. Use e.g:

    long double m = sqrt(static_cast<long double>(n));
    

    As you include cmath not math.h I'm assuming you want c++. For C, you'll need to use e.g:

    double m = sqrt((double) n);
    

    The error you get simply means that the compiler cannot automatically select a sqrt function for you - the integer you pass needs to be converted to a floating point type, and the compiler doesn't know which floating point type and sqrt function it should select.