C++ 中的 sqrt、sqrtl 和 sqrtf


在 C++ 的 cmath 库中,除了 sqrt 之外,还有其他用于获取平方根的函数。sqrt 函数主要用于双精度浮点数类型输入。其他函数则用于浮点数、长整型数据等。让我们看看这些函数的用法。

sqrt() 函数

此函数用于双精度浮点数类型数据。因此,它返回双精度浮点数类型的平方根。语法如下所示。

double sqrt(double argument)

示例

#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
main() {
   double x = 144.0;
   double y = 180.0;
   cout << fixed << setprecision(12) << sqrt(x) << endl;
   cout << fixed << setprecision(12) << sqrt(y) << endl;
}

输出

12.000000000000
13.416407864999

请注意,我们必须传入参数,否则会返回错误。如果参数为负数,则也会返回 NaN。

sqrtf() 函数

此函数用于浮点数类型数据。因此,它返回浮点数类型的平方根。语法如下所示。

float sqrtf(float argument)

示例

#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
main() {
   float x = 144.0;
   float y = 180.0;
   cout << fixed << setprecision(6) << sqrtf(x) << endl;
   cout << fixed << setprecision(6) << sqrtf(y) << endl;
}

输出

12.000000
13.416408

请注意,我们必须传入参数,否则会返回错误。如果参数为负数,则也会返回 NaN。

sqrtl() 函数

此函数用于长双精度浮点数类型数据。因此,它返回长双精度浮点数类型的平方根。它是具有更高精度的双精度浮点数。当我们使用 1018 数量级的整数时,此函数很有用。

long double sqrtl(long double argument)

示例

#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
main() {
   long long int x = 5000000000000000000;
   long long int y = 999999999999999999;
   cout << fixed << setprecision(12) << sqrtl(x) << endl;
   cout << fixed << setprecision(12) << sqrtl(y) << endl;
}

输出

2236067977.499789696420
999999999.999999999476

更新于: 2019-07-30

804 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.