C++中的QRT、SqRTL和SqRTF

在C++库中有各种可用的函数来计算 数的平方根 .最重要的是, sqrt 被使用了。需要 双重的 作为论据。这个 header定义了另外两个内置函数,用于计算具有类型参数的数字(除sqrt外)的平方根 浮动 长双人 因此,C++中计算平方根的所有函数都是:

null

作用

资料型态

sqrt

双重的

sqrtf

浮动

sqrtl

长双人

下面详细讨论了这些功能:

A) 双sqrt(双参数) :它返回要键入double的数字的平方根。

语法:

double sqrt(double arg)

CPP

// CPP code to illustrate the use of sqrt function
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
// Driver Code
int main()
{
double val1 = 225.0;
double val2 = 300.0;
cout << fixed << setprecision(12) << sqrt (val1) << endl;
cout << fixed << setprecision(12) << sqrt (val2) << endl;
return (0);
}


输出

15.000000000000
17.320508075689

与此功能相关的错误和异常:

1. 必须给出两个论点,否则将给出一个 错误:没有匹配函数 对于如下所示的对“sqrt()”的调用,

CPP

// CPP Program to demonstrate errors in double sqrt()
#include <cmath>
#include <iostream>
using namespace std;
// Driver Code
int main()
{
double answer;
answer = sqrt ();
cout << "Square root of " << a << " is " << answer
<< endl;
return 0;
}


输出

prog.cpp:9:19: error: no matching function for call to ‘sqrt()’
     answer = sqrt();

2. 如果我们在参数域中传递负值,就会发生错误,输出将是 -a的平方根,也就是-nan。

CPP

// CPP Program to demonstrate errors in double sqrt()
#include <cmath>
#include <iostream>
using namespace std;
// Driver Code
int main()
{
double a = -2, answer;
answer = sqrt (a);
cout << "Square root of " << a << " is " << answer
<< endl;
return 0;
}


输出:

Square root of -2 is -nan

B) 浮动sqrtf(浮动参数) :返回一个数字的平方根,输入float。

语法:

float sqrtf(float arg)

CPP

// CPP code to illustrate the use of sqrtf function
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
float val1 = 225.0;
float val2 = 300.0;
cout << fixed << setprecision(12) << sqrtf(val1)
<< endl;
cout << fixed << setprecision(12) << sqrtf(val2)
<< endl;
return (0);
}


输出

15.000000000000
17.320508956909

C) 长双sqrtl(长双参数) :它返回数字的平方根,以更精确地键入long double。

sqrtl功能的优点: 使用10阶整数时 18 ,用 sqrt 由于编程语言中的默认函数使用浮点/双精度,函数可能会由于精度错误而给出错误的答案。但这总会给出一个准确的答案。

语法:

long double sqrtl(long double arg)

下面给出的一个示例显示了使用sqrt和sqrtl处理长整数时的确切区别,

1) 使用sqrt函数:

CPP

// CPP code to illustrate the incorrectness of sqrt
// function
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
long long int val1 = 1000000000000000000;
long long int val2 = 999999999999999999;
cout << fixed << setprecision(12) << sqrt (val1) << endl;
cout << fixed << setprecision(12) << sqrt (val2) << endl;
return (0);
}


输出

1000000000.000000000000
1000000000.000000000000

2) 使用sqrtl函数:

CPP

// CPP code to illustrate the correctness of sqrtl function
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
long long int val1 = 1000000000000000000;
long long int val2 = 999999999999999999;
cout << fixed << setprecision(12) << sqrtl(val1)
<< endl;
cout << fixed << setprecision(12) << sqrtl(val2)
<< endl;
return (0);
}


输出

1000000000.000000000000
999999999.999999999476

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享