std:: sqrt, std:: sqrtf, std:: sqrtl
|
定义于头文件
<cmath>
|
||
| (1) | ||
|
float
sqrt
(
float
num
)
;
double
sqrt
(
double
num
)
;
|
(C++23 前) | |
|
/*floating-point-type*/
sqrt ( /*floating-point-type*/ num ) ; |
(C++23 起)
(C++26 起为 constexpr) |
|
|
float
sqrtf
(
float
num
)
;
|
(2) |
(C++11 起)
(C++26 起为 constexpr) |
|
long
double
sqrtl
(
long
double
num
)
;
|
(3) |
(C++11 起)
(C++26 起为 constexpr) |
|
SIMD 重载
(C++26 起)
|
||
|
定义于头文件
<simd>
|
||
|
template
<
/*math-floating-point*/
V
>
constexpr
/*deduced-simd-t*/
<
V
>
|
(S) | (C++26 起) |
|
附加重载
(C++11 起)
|
||
|
定义于头文件
<cmath>
|
||
|
template
<
class
Integer
>
double sqrt ( Integer num ) ; |
(A) | (C++26 起为 constexpr) |
std::sqrt
的重载版本作为参数类型。
(since C++23)
|
S)
SIMD 重载对
v_num
执行逐元素的
std::sqrt
运算。
|
(since C++26) |
|
A)
为所有整数类型提供了额外的重载,这些类型被视为
double
。
|
(since C++11) |
目录 |
参数
| num | - | 浮点数或整数值 |
返回值
如果未发生错误,则返回 num 的平方根 ( √ num )。
如果发生定义域错误,则返回一个由实现定义的值(在支持 NaN 的情况下返回 NaN)。
如果由于下溢发生范围错误,将返回正确结果(舍入后)。
错误处理
错误报告方式遵循 math_errhandling 中的规范。
当 num 小于零时会发生定义域错误。
如果实现支持 IEEE 浮点算术 (IEC 60559),
- 若参数小于 -0,将引发 FE_INVALID 并返回 NaN。
- 若参数为 +∞ 或 ±0,则直接返回原值。
- 若参数为 NaN,则返回 NaN。
注释
std::sqrt
根据 IEEE 标准要求对无限精确结果进行正确舍入。特别地,如果精确结果可以用浮点类型表示,则必须产生该精确结果。其他有此要求的运算只有
算术运算符
和函数
std::fma
。其他函数(包括
std::pow
)则不受此约束。
额外的重载并不需要完全按照 (A) 的形式提供。它们只需确保对于整数类型的实参 num , std :: sqrt ( num ) 能够产生与 std :: sqrt ( static_cast < double > ( num ) ) 相同的效果。
示例
#include <cerrno> #include <cfenv> #include <cmath> #include <cstring> #include <iostream> // #pragma STDC FENV_ACCESS ON int main() { // 常规用法 std::cout << "sqrt(100) = " << std::sqrt(100) << '\n' << "sqrt(2) = " << std::sqrt(2) << '\n' << "golden ratio = " << (1 + std::sqrt(5)) / 2 << '\n'; // 特殊值 std::cout << "sqrt(-0) = " << std::sqrt(-0.0) << '\n'; // 错误处理 errno = 0; std::feclearexcept(FE_ALL_EXCEPT); std::cout << "sqrt(-1.0) = " << std::sqrt(-1) << '\n'; if (errno == EDOM) std::cout << " errno = EDOM " << std::strerror(errno) << '\n'; if (std::fetestexcept(FE_INVALID)) std::cout << " FE_INVALID raised\n"; }
可能的输出:
sqrt(100) = 10
sqrt(2) = 1.41421
golden ratio = 1.61803
sqrt(-0) = -0
sqrt(-1.0) = -nan
errno = EDOM Numerical argument out of domain
FE_INVALID raised
另请参阅
|
(C++11)
(C++11)
|
计算一个数的指定次幂 (
x
y
)
(函数) |
|
(C++11)
(C++11)
(C++11)
|
计算立方根 (
3
√
x
)
(函数) |
|
(C++11)
(C++11)
(C++11)
|
计算斜边长
√
x
2
+y 2 和 √ x 2 +y 2 +z 2 (C++17 起) (函数) |
|
计算右半平面范围内的复数平方根
(函数模板) |
|
|
对 valarray 的每个元素应用函数
std::sqrt
(函数模板) |
|
|
C 文档
for
sqrt
|
|