sqrt, sqrtf, sqrtl

2025-11-25 22:17:13

定义于头文件

float sqrtf( float arg );

(1)

(C99 起)

double sqrt( double arg );

(2)

long double sqrtl( long double arg );

(3)

(C99 起)

定义于头文件

#define sqrt( arg )

(4)

(C99 起)

1-3) 计算 arg 的平方根。

4) 泛型宏:若 arg 拥有 long double 类型,则调用 sqrtl 。否则,若 arg 拥有整数类型或 double 类型,则调用 sqrt 。否则调用 sqrtf 。若 arg 为复数或虚数,则宏调用对应复数函数( csqrtf 、 csqrt 、 csqrtl )。

参数

arg

-

浮点值

返回值

若不出现错误,则返回 arg 的平方根( \({\small \sqrt{arg} }\)√arg )。

若出现定义域错误,则返回实现定义值(支持的平台上为 NaN )。

若出现下溢所致的值域错误,则返回(舍入后的)正确结果。

错误处理

报告 math_errhandling 中指定的错误。

若 arg 小于零则出现定义域错误。

若实现支持 IEEE 浮点算术( IEC 60559 ),则

若参数小于 -0 ,则引发 FE_INVALID 并返回 NaN 。

若参数为 +∞ 或 ±0 ,则返回不修改的参数。

若参数为 NaN ,则返回 NaN 。

注解

IEEE 标准要求 sqrt 为准确。其他要求为准确的运算只有算术运算符和函数 fma 。舍入到返回类型后(用默认舍入模式), sqrt 的结果与无限精度结果不可辨别。换言之,误差小于 0.5 ulp 。其他函数,含 pow ,不受这种制约。

示例

运行此代码

#include

#include

#include

#include

#pragma STDC FENV_ACCESS ON

int main(void)

{

// 正常使用

printf("sqrt(100) = %f\n", sqrt(100));

printf("sqrt(2) = %f\n", sqrt(2));

printf("golden ratio = %f\n", (1+sqrt(5))/2);

// 特殊值

printf("sqrt(-0) = %f\n", sqrt(-0.0));

// 错误处理

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 standard (ISO/IEC 9899:2011):

7.12.7.5 The sqrt functions (p: 249)

7.25 Type-generic math (p: 373-375)

F.10.4.5 The sqrt functions (p: 525)

C99 standard (ISO/IEC 9899:1999):

7.12.7.5 The sqrt functions (p: 229-230)

7.22 Type-generic math (p: 335-337)

F.9.4.5 The sqrt functions (p: 462)

C89/C90 standard (ISO/IEC 9899:1990):

4.5.5.2 The sqrt function

参阅

powpowfpowl(C99)(C99)

计算一个数的给定次幂( \(\small{x^y}\)xy ) (函数)

cbrtcbrtfcbrtl(C99)(C99)(C99)

计算立方根( \(\small{\sqrt[3]{x} }\)3√x ) (函数)

hypothypotfhypotl(C99)(C99)(C99)

计算两个给定数平方和的平方根 ( \(\scriptsize{\sqrt{x^2+y^2} }\)√x2+y2 ) (函数)

csqrtcsqrtfcsqrtl(C99)(C99)(C99)

计算复数平方根 (函数)

Copyright © 2022 角动游戏活动平台 - 全网网游动态实时追踪 All Rights Reserved.