Visual Studio 2008编译器是否在C++中使用sqrt加倍自动加密?

Chr*_*_45 4 c++ casting sqrt

编译器不应该自动转换成下面的double吗?至少根据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
Run Code Online (Sandbox Code Playgroud)

Sco*_*ith 8

问题是有三个版本sqrt可供选择:

     double sqrt (      double x );
      float sqrt (       float x );
long double sqrt ( long double x );
Run Code Online (Sandbox Code Playgroud)

因为你传入了一个int,编译器会提升你的参数,但同样有效的是将你的整数提升为任何上述类型,所以它是不明确的.

您可以通过简单地转换为上述类型之一来解决此问题,如:

cout << "The square root of k is: " << sqrt((double)k) << endl;
Run Code Online (Sandbox Code Playgroud)

  • 或者因为这是C++ static_cast所以你以后可以搜索它. (2认同)