gpt4 book ai didi

c++ - sqrt 和 sqrtf 的区别

转载 作者:IT老高 更新时间:2023-10-28 21:41:41 31 4
gpt4 key购买 nike

我想考虑编码。首先是:

#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main() {
int s = 25;
cout << sqrt(s) << endl;
return 0;
}

它给了我这个错误:

>c:\users\datuashvili\documents\visual studio 2010\projects\training\training\training.cpp(9): error C2668: 'sqrt' : ambiguous call to overloaded function
1> c:\program files\microsoft visual studio 10.0\vc\include\math.h(589): could be 'long double sqrt(long double)'
1> c:\program files\microsoft visual studio 10.0\vc\include\math.h(541): or 'float sqrt(float)'
1> c:\program files\microsoft visual studio 10.0\vc\include\math.h(127): or 'double sqrt(double)'
1> while trying to match the argument list '(int)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

如果我在 s 前面的括号中添加类型 float,如下所示:

#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;

int main() {
int s = 25;
cout << sqrt((float)s) << endl;
return 0;
}

我猜到了,5。另一个变体是,如果我写的是 sqrtf,而不是 sqrt:

#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;

int main(){
int s=25;
cout << sqrtf((float)s) << endl;
return 0;
}

我也得到了5

它们之间有什么区别?是不是表示sqrtf和float类型的sqrt一样?

最佳答案

这里是 a page on MSDN documentation for sqrt() and sqrtf() ,这就解释了差异:

sqrt, sqrtf

Calculates the square root.

    double sqrt(
double x
);
float sqrt(
float x
); // C++ only
long double sqrt(
long double x
); // C++ only
float sqrtf(
float x
);

Parameters

x: Nonnegative floating-point value

Remarks

C++ allows overloading, so users can call overloads of sqrt that take float or long double types. In a C program, sqrt always takes and returns double.

Return Value

The sqrt function returns the square-root of x. If x is negative, sqrt returns an indefinite, by default.

所以 C++ 的不同之处在于 sqrt() 接受 doublefloatlong doublesqrtf() 只接受 float

正如文档所说,有两个不同版本的唯一原因是因为 C 不支持重载,所以必须有两个函数。 C++ 允许重载,因此实际上有三种不同版本的 sqrt() 采用不同大小的浮点参数。

因此,在 C++ 中,您的两个代码片段基本上都做同样的事情。然而,在 C 中,在 sqrt() 调用中会发生从 floatdouble 的转换。

关于c++ - sqrt 和 sqrtf 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7431040/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com