这里为什么会出现错误?
#include <iostream>
#include <math.h>
#include <vector>
#include <ostream>
using namespace std;
struct Point {
int x,y;
};
int distance (const Point& a,const Point& b){
int k= sqrt(((a.x-b.x)*(a.x-b.x))+((a.y-b.y)*(a.y-b.y)));
}
int main(){
return 0;
}
构建输出:
1>------ Build started: Project: distance, Configuration: Debug Win32 ------
1> distance.cpp
1>d:\...\distance.cpp(13): error C2668: 'sqrt' : ambiguous call to overloaded function
1> c:\...\vc\include\math.h(589): could be 'long double sqrt(long double)'
1> c:\...\vc\include\math.h(541): or 'float sqrt(float)'
1> c:\...\vc\include\math.h(127): or 'double sqrt(double)'
1> while trying to match the argument list '(const int)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
最佳答案
sqrt
有3个重载采用不同的参数:float sqrt(float)
, double sqrt(double)
和 long double sqrt(long double)
.您可以在编译器输出中看到这些。
如果您调用 sqrt
使用整数参数,如 sqrt(9)
,整数可以转换为这三种类型中的任何。那么应该调用哪个函数呢?编译器不知道。它是模棱两可的,所以你会得到一个错误,迫使你明确选择你想要的重载。只需转换参数以匹配这样的重载之一:sqrt(static_cast<float>(((a.x-b.x)*(a.x-b.x))+((a.y-b.y)*(a.y-b.y)))
.
关于c++ - C++中的sqrt问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4217592/