sqrt
在头文件<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
 
注意
sqrt是IEEE标准所要求的。唯一需要确定的其他操作是算术运算符和函数fma。在舍入到返回类型(使用默认舍入模式)后,结果sqrt与无限精确的结果无法区分。换句话说,误差小于0.5 ulp。其他功能,包括pow,并不那么受到限制。
示例
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.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参考
- C11标准(ISO/IEC 9899:2011): 
- 7.12.7.5 sqrt函数(p:249)
 - 7.25类型通用数学<tgmath.h>(p:373-375)
 - F.10.4.5 sqrt函数(p:525)
 
 - C99标准(ISO/IEC 9899:1999): 
- 7.12.7.5 sqrt函数(p:229-230)
 - 7.22类型通用数学<tgmath.h>(p:335-337)
 - F.9.4.5 sqrt函数(p:462)
 
 - C89/C90标准(ISO/IEC 9899:1990): 
- 4.5.5.2 sqrt函数
 
 
See also
powpowfpowl (C99)(C99)  | computes a number raised to the given power (xy) (function)  | 
|---|---|
cbrtcbrtfcbrtl (C99)(C99)(C99)  | computes cubic root (3√x) (function)  | 
hypothypotfhypotl (C99)(C99)(C99)  | computes square root of the sum of the squares of two given numbers (√x2+y2) (function)  | 
csqrtcsqrtfcsqrtl (C99)(C99)(C99)  | computes the complex square root (function)  | 
| C++ documentation for sqrt |
 © cppreference.comLicensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

