Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't the Visual Studio 2008 compiler autocast to double with sqrt in C++?

Tags:

c++

casting

sqrt

Shouldn't the compiler automatically cast to a double in the following? At least according to Walter Savitch.

#include <iostream>
#include <cmath>
using namespace std;

int main(){
    int k;
    for(k = 1; k <= 10; k++)
        cout << "The square root of k is: " << sqrt(k) << endl;
    return 0;
}//error C2668: 'sqrt' : ambiguous call to overloaded function
//Visual Studio 2008 on Win Vista
like image 473
Chris_45 Avatar asked Dec 18 '22 02:12

Chris_45


1 Answers

The problem is that there are three versions of sqrt to choose from:

     double sqrt (      double x );
      float sqrt (       float x );
long double sqrt ( long double x );

Since you're passing in an int, the compiler is going to promote your argument but it's equally valid to promote your integer to any of the above types, so it's ambiguous.

You can fix this by simply explicitly casting to one of the above types, as in:

cout << "The square root of k is: " << sqrt((double)k) << endl;
like image 127
Scott Smith Avatar answered Dec 24 '22 02:12

Scott Smith