编译器不应该自动转换成下面的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)
问题是有三个版本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)
| 归档时间: |
|
| 查看次数: |
1450 次 |
| 最近记录: |