#include <math.h>
// double sqrt(double x); // 回傳 √x,x < 0 定義域錯誤,回傳 NaN
#include <stdio.h>
#include <math.h>
int main() {
double x = 4.0;
double result = sqrt(x);
printf("√%.2f = %.2f\n", x, result); // √4.00 = 2.00
// 編譯需連結數學庫
// gcc main.c -o main -lm
return 0;
}
<math.h>。-lm**(libm),MSVC 預設連結。x >= 0。負數輸入行為:C99 回傳 NaN 並設定 errno = EDOM。sqrtf(float)、sqrtl(long double)(C99)。// 整數開根(向下取整)
long long isqrt(long long x) {
long long r = (long long)sqrt((double)x);
while ((r+1)*(r+1) <= x) ++r;
while (r*r > x) --r;
return r;
}
// 判斷完全平方數
bool isPerfectSquare(long long x) {
if (x < 0) return false;
long long r = isqrt(x);
return r*r == x;
}
sqrt 是標準庫提供的高效、精確開根函數。記住 #include <math.h> 與 -lm 連結選項,注意定義域與浮點數精度特性即可正確使用。