dat*_*ili 13 c++ floating-point
我想考虑编码.首先它是:
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main() {
int s = 25;
cout << sqrt(s) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它给了我这个错误:
>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 ==========
Run Code Online (Sandbox Code Playgroud)
如果我在s前面的括号中添加float类型,如下所示:
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main() {
int s = 25;
cout << sqrt((float)s) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
正如我猜的那样,我得到了5.另一种变体是sqrt,如果我写,而不是sqrtf:
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main(){
int s=25;
cout << sqrtf((float)s) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我也有5.
他们之间有什么区别?这是否意味着float类型的sqrtf与sqrt相同?
In *_*ico 16
下面是在MSDN文档页面sqrt()和sqrtf(),解释的区别:
sqrt,sqrtf
计算平方根.
Run Code Online (Sandbox Code Playgroud)double sqrt( double x ); float sqrt( float x ); // C++ only long double sqrt( long double x ); // C++ only float sqrtf( float x );参数
x:非负浮点值
备注
C++允许重载,因此用户可以调用带有 float或long double类型的sqrt的重载 .在C程序中,sqrt始终采用并返回double.
回报价值
的SQRT函数返回x的平方根.如果x为负数,则默认情况下sqrt返回无限期.
所以C++的不同之处在于sqrt()接受a double,a float或a long doublewhile sqrtf()只接受a float.
正如文档所说,有两个不同版本的唯一原因是因为C不支持重载,所以必须有两个函数.C++允许重载,因此实际上有三种不同版本sqrt()的不同大小的浮点参数.
所以在C++中,你的代码片段基本上都是一样的.在C,然而,就已经从一个转换float到double在sqrt()通话.
| 归档时间: |
|
| 查看次数: |
42631 次 |
| 最近记录: |