c++ - 歧义平方根

标签 c++ sqrt

<分区>

Possible Duplicate:
C++ compiler error: ambiguous call to overloaded function

只是将 pdf 中的一些代码复制到 C++builder XE2 和 visual studio express 2012 中。这两个编译器都给出了关于歧义的错误代码。我刚开始,所以我真的不知道该怎么做。也许我的教科书(pdf)现在已经过时了?它被称为“14 天学习 C++”。无论如何,这是复制的代码。

#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#pragma hdrstop
void getSqrRoot(char* buff, int x);
int main(int argc, char** argv)
{
int x;
char buff[30];
cout << “Enter a number: “;
cin >> x;
getSqrRoot(buff, x);
cout << buff;
getch();
}
void getSqrRoot(char* buff, int x)
{
sprintf(buff, “The sqaure root is: %f”, sqrt(x));
}

我在c++builder中得到的错误代码是:

[BCC32 错误] SquareRoot.cpp(19): E2015 std::sqrt(float) at c:\program files (x86)\embarcadero\rad studio\9.0\include\windows\crtl\math 之间的歧义。 h:266' 和 'std::sqrt(long double) 在 c:\program files (x86)\embarcadero\rad studio\9.0\include\windows\crtl\math.h:302' 完整的解析器上下文 SquareRoot.cpp(18): 解析:void getSqrRoot(char *,int)

附带说明一下,我的 pdf 手册中的引号与我输入的普通 "字符不同。这些 "也不与编译器兼容。也许有人也知道解决这个问题的方法吗?提前致谢。

最佳答案

像这样更改您的代码:

void getSqrRoot(char* buff, int x)
{
 sprintf(buff, “The sqaure root is: %f”, sqrt((float)x));
}

因为平方根是重载函数编译器没有机会从 int x 值隐式转换为 float 或 double 值,您需要直接进行。

Compiler: see sqrt(int) -> what to choose? sqrt(float)/sqrt(double) ?
Compiler: see sqrt((float)int) -> sqrt(float), ok!
Compeler: see sqrt((double)int) -> sqrt(double), ok!

关于c++ - 歧义平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13874096/

相关文章:

c++ - 在 Linux 下使用连字符或下划线作为文件的单词分隔符

python - 用于最小内存开销的最佳 GUI 制造商

logarithm - 使用 sqrt() 查找 log2()

c - 为什么这个 C 函数(求 n 的平方根的牛顿拉夫逊法)不能正常工作?

<cmath> SQRT() 的 c++ 实用计算复杂度

c - 快速反演算法比 math.h 1/sqrt 函数慢

c++ - 将 ASCII std::string 转换为十六进制

c++ - 是否建议将指向堆内存的指针始终声明为 `const`?

c++ - 传递指针地址

css - 如何获取按钮值中的 sqrt 符号?