c++ - C++中的sqrt问题

标签 c++

这里为什么会出现错误?

#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/

相关文章:

c++ - 旋转使用 OpenGL 绘制的 2D 对象

c++ - Vector of Vector of (member) 函数指针

c++ - 如何在两个不同大小的 vector 中找到公共(public)数字

c++ - 在 C++ 中获取选项卡 URL

c++ - 如何根据自定义操作中设置的属性安装功能?

c++ - Windows 应用商店应用程序 - 删除 fullTrustCapability

c++ - 一致性哈希 SHA1 模运算

c++ - 使用inline内联汇编器对带有进位的bigint add进行编码

c++ - 当我有 iostream 和没有时,结果会有所不同,但没有错误

c++ - C1202 : recursive type or function dependency context too complex