sqrt, sqrtf, sqrtl
來自 cppreference.com
定義於標頭檔案 <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 時返回 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 平方根函式 (p: TBD)
- 7.25 型別通用數學 <tgmath.h> (p: TBD)
- F.10.4.5 平方根函式 (p: TBD)
- C17 標準 (ISO/IEC 9899:2018)
- 7.12.7.5 平方根函式 (p: TBD)
- 7.25 型別通用數學 <tgmath.h> (p: TBD)
- F.10.4.5 平方根函式 (p: TBD)
- C11 標準 (ISO/IEC 9899:2011)
- 7.12.7.5 平方根函式 (p: 249)
- 7.25 型別通用數學 <tgmath.h> (p: 373-375)
- F.10.4.5 平方根函式 (p: 525)
- C99 標準 (ISO/IEC 9899:1999)
- 7.12.7.5 平方根函式 (p: 229-230)
- 7.22 型別通用數學 <tgmath.h> (p: 335-337)
- F.9.4.5 平方根函式 (p: 462)
- C89/C90 標準 (ISO/IEC 9899:1990)
- 4.5.5.2 平方根函式
[編輯] 另請參閱
(C99)(C99) |
計算給定冪的數字 (xy) (函式) |
(C99)(C99)(C99) |
計算立方根 (3√x) (函式) |
(C99)(C99)(C99) |
計算兩個給定數字的平方和的平方根(√x2 +y2 ) (函式) |
(C99)(C99)(C99) |
計算復平方根 (函式) |
C++ 文件,關於 sqrt
|