C++库中有多种函数可用于计算数字的平方根。最突出的是使用 sqrt。它以双重作为论据。 header 定义了另外两个内置函数,用于计算一个数字(sqrt 除外)的平方根,该数字的参数类型为float和long double。因此,用于计算C++平方根的所有函数都是:
方法 | 数据类型 |
---|---|
sqrt | double |
sqrtf | float |
sqrtl | long double |
下面详细讨论了这些功能:
A) double sqrt(double arg): 它返回一个数字的平方根以键入 double。
语法:
double sqrt(double arg)
// CPP代码说明sqrt函数的使用
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
// 驱动程序代码
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
时间复杂度: O(√n) 辅助空间: O(1)
1. 必须给出参数,否则它会给出一个错误,没有匹配函数来调用 'sqrt()',如下所示,
// CPP程序演示双sqrt()中的错误
#include <cmath>
#include <iostream>
using namespace std;
// 驱动程序代码
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();
时间复杂度: O(√n) 辅助空间: O(1)
2. 如果我们在参数域中传递负值,则会发生错误,输出将是 -a 的平方根,即 -nan。
// CPP程序演示双sqrt()中的错误
#include <cmath>
#include <iostream>
using namespace std;
// 驱动程序代码
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
时间复杂度: O(√n) 辅助空间: O(1) B) 浮点数 sqrtf(浮点参数) :它返回一个数字的平方根以键入浮点数。
语法:
float sqrtf(float arg)
// CPP代码说明sqrtf函数的使用
#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
时间复杂度: O(√n) 辅助空间: O(1) C) 长双精度 sqrtl(长双参数) :它返回数字的平方根以更精确地键入长双精度。
sqrtl 函数的优点: 处理 10 阶整数时18,使用sqrt函数计算其平方根可能会由于精度错误而给出不正确的答案,因为编程语言中的默认函数适用于浮点数/双精度数。但这总会给出准确的答案。 语法:
long double sqrtl(long double arg)
下图显示了使用 sqrt 和 sqrtl 处理长整数时的确切区别, 1) 使用 sqrt 函数:
// 用于说明sqrt函数错误的CPP代码
#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
时间复杂度: O(√n) 辅助空间: O(1)
2)使用sqrtl函数:
// 用于说明sqrtl函数正确性的CPP代码
#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
时间复杂度: O(√n) 辅助空间: O(1)
如果大家发现什么不正确的地方,或者你想分享有关上述的更多内容,可以在下面评论。