sqrt, sqrtf, sqrtl
来自 cppreference.cn
定义于头文件 <math.h> |
||
float sqrtf( float arg ); |
(1) | (C99 起) |
double sqrt( double arg ); |
(2) | |
long double sqrtl( long double arg ); |
(3) | (C99 起) |
定义于头文件 <tgmath.h> |
||
#define sqrt( arg ) |
(4) | (C99 起) |
1-3) 计算 arg 的平方根。
4) 类型泛型宏: 如果 arg 的类型为 long double,则调用
sqrtl
。 否则,如果 arg 具有整数类型或类型 double,则调用 sqrt
。 否则,调用 sqrtf
。 如果 arg 是复数或虚数,则此宏调用相应的复数函数 (csqrtf, csqrt, csqrtl)。内容 |
[编辑] 参数
arg | - | 浮点数值 |
[编辑] 返回值
若未发生错误,则返回 arg 的平方根 (√arg)。
若发生域错误,则返回实现定义的数值(若支持则为 NaN)。
若因下溢而发生范围错误,则返回正确结果(舍入后)。
[编辑] 错误处理
错误报告方式见 math_errhandling
。
当 arg 小于零时,发生域错误。
若实现支持 IEEE 浮点算术 (IEC 60559),
- 若参数小于 -0,则引发 FE_INVALID 并返回 NaN。
- 若参数为 +∞ 或 ±0,则原样返回,不修改。
- 若参数为 NaN,则返回 NaN。
[编辑] 注解
IEEE 标准要求 sqrt
必须从无限精确的结果正确舍入。 特别地,如果精确结果可以表示为浮点类型,则生成该结果。 唯一其他要求如此的操作是算术运算符和函数 fma。 其他函数,包括 pow,则不受此约束。
[编辑] 示例
运行此代码
#include <errno.h> #include <fenv.h> #include <math.h> #include <stdio.h> // #pragma STDC FENV_ACCESS ON int main(void) { // normal use printf("sqrt(100) = %f\n", sqrt(100)); printf("sqrt(2) = %f\n", sqrt(2)); printf("golden ratio = %f\n", (1 + sqrt(5)) / 2); // special values printf("sqrt(-0) = %f\n", sqrt(-0.0)); // error handling errno = 0; feclearexcept(FE_ALL_EXCEPT); printf("sqrt(-1.0) = %f\n", sqrt(-1)); if (errno == EDOM) perror(" errno == EDOM"); if (fetestexcept(FE_INVALID)) puts(" FE_INVALID was raised"); }
可能的输出
sqrt(100) = 10.000000 sqrt(2) = 1.414214 golden ratio = 1.618034 sqrt(-0) = -0.000000 sqrt(-1.0) = -nan errno = EDOM: Numerical argument out of domain FE_INVALID was raised
[编辑] 参考
- C23 标准 (ISO/IEC 9899:2024)
- 7.12.7.5 The sqrt functions (p: TBD)
- 7.25 Type-generic math <tgmath.h> (p: TBD)
- F.10.4.5 The sqrt functions (p: TBD)
- C17 标准 (ISO/IEC 9899:2018)
- 7.12.7.5 The sqrt functions (p: TBD)
- 7.25 Type-generic math <tgmath.h> (p: TBD)
- F.10.4.5 The sqrt functions (p: TBD)
- C11 标准 (ISO/IEC 9899:2011)
- 7.12.7.5 The sqrt functions (p: 249)
- 7.25 Type-generic math <tgmath.h> (p: 373-375)
- F.10.4.5 The sqrt functions (p: 525)
- C99 标准 (ISO/IEC 9899:1999)
- 7.12.7.5 The sqrt functions (p: 229-230)
- 7.22 Type-generic math <tgmath.h> (p: 335-337)
- F.9.4.5 The sqrt functions (p: 462)
- C89/C90 标准 (ISO/IEC 9899:1990)
- 4.5.5.2 The sqrt function
[编辑] 参见
(C99)(C99) |
计算给定数的幂次 (xy) (函数) |
(C99)(C99)(C99) |
计算立方根 (3√x) (函数) |
(C99)(C99)(C99) |
计算两个给定数平方和的平方根 (√x2 +y2 ) (函数) |
(C99)(C99)(C99) |
计算复数平方根 (函数) |
C++ 文档 关于 sqrt
|