Share via


sqrt, sqrtf, sqrtl

計算平方根。

語法

double sqrt(
   double x
);
float sqrt(
   float x
);  // C++ only
long double sqrt(
   long double x
);  // C++ only
float sqrtf(
   float x
);
long double sqrtl(
   long double x
);
#define sqrt(x) // Requires C11 or higher

參數

x
非負值浮點值

備註

因為 C++ 允許多載,所以您可以呼叫採用 sqrtfloat 類型的 long double 的多載。 在 C 程式中,除非您使用 <tgmath.h> 宏來呼叫此函式, sqrt 否則一律會採用 並傳 double 回 。

如果您使用 <tgmath.h> sqrt() 宏,引數的類型會決定選取哪一個函式版本。 如需詳細資訊,請參閱 類型泛型數學

根據預設,此函式的全域狀態會限定于應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。

傳回值

sqrt 函式會傳回 x 的平方根。 根據預設,如果 x 為負數, sqrt 則會傳回無限期 NaN

輸入 SEH 例外狀況 _matherr 例外
± QNaN,IND none _DOMAIN
-Inf none _DOMAIN
x < 0 none _DOMAIN

需求

函式 C 標頭 C++ 標頭
sqrt, sqrtf, sqrtl <math.h> <cmath>
sqrt 宏觀 <tgmath.h>

如需相容性資訊,請參閱相容性

範例

// crt_sqrt.c
// This program calculates a square root.

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

int main( void )
{
   double question = 45.35, answer;
   answer = sqrt( question );
   if( question < 0 )
      printf( "Error: sqrt returns %f\n", answer );
   else
      printf( "The square root of %.2f is %.2f\n", question, answer );
}
The square root of 45.35 is 6.73

另請參閱

數學和浮點支援
exp, expf, expl
log, logf, log10, log10f
pow, powf, powl
_CIsqrt