sqrt 是 "square root"(平方根)的缩写,它是 C 标准库数学函数的一部分,用于计算一个非负数的平方根。

(图片来源网络,侵删)
核心要点:包含头文件
在使用 sqrt 函数之前,你必须在你的 C 程序中包含 <math.h> 头文件,这是最常见的一个错误,很多人会忘记它。
#include <math.h>
函数原型
sqrt 函数的原型如下:
double sqrt(double x);
- 功能:计算
x的平方根。 - 参数:
x:一个double类型的数值。- 重要:
x必须是一个非负数(x >= 0),如果传入负数,结果将是 "NaN" (Not a Number),并且会设置错误标志。
- 返回值:
- 返回一个
double类型的值,即x的平方根。 x是负数,函数会返回 NaN,并且会通过errno(一个全局错误码变量)来报告错误(errno会被设置为EDOM,表示域错误)。
- 返回一个
使用示例
下面是一个完整的、可运行的 C 程序示例,展示了 sqrt 的基本用法。
#include <stdio.h> // 用于 printf
#include <math.h> // 用于 sqrt
#include <errno.h> // 用于检查 errno
int main() {
double number, result;
// 示例 1: 计算一个正数的平方根
number = 25.0;
result = sqrt(number);
printf("The square root of %.2f is %.4f\n", number, result); // 输出: The square root of 25.00 is 5.0000
// 示例 2: 计算一个小数的平方根
number = 2.0;
result = sqrt(number);
printf("The square root of %.2f is %.4f\n", number, result); // 输出: The square root of 2.00 is 1.4142
// 示例 3: 计算 0 的平方根
number = 0.0;
result = sqrt(number);
printf("The square root of %.2f is %.4f\n", number, result); // 输出: The square root of 0.00 is 0.0000
// 示例 4: 尝试计算负数的平方根 (错误处理)
number = -9.0;
errno = 0; // 在调用前重置 errno
result = sqrt(number);
// 检查 errno 是否被设置
if (errno == EDOM) {
printf("Error: Cannot calculate the square root of a negative number.\n");
} else {
// 如果没有错误,正常打印结果
printf("The square root of %.2f is %.4f\n", number, result);
}
return 0;
}
编译时的注意事项:链接数学库
在 Linux 或 macOS 系统上,当你编译使用了 <math.h> 中函数的程序时,通常需要手动链接数学库,这通过编译器(如 gcc)的 -lm 选项来实现。

(图片来源网络,侵删)
命令格式:
gcc your_program.c -o your_program -lm
gcc:编译器名称。your_program.c:你的源代码文件。-o your_program:指定输出的可执行文件名。-lm:告诉链接器去链接数学库libm.a。m代表 math。
为什么需要 -lm?
像 printf 这样的函数是 C 标准库的一部分,编译器默认会链接它,而 sqrt 等数学函数在单独的数学库中,需要显式地告诉编译器去链接它,如果你忘记加 -lm,编译时会报类似 "undefined reference to `sqrt'" 的错误。
在 Windows (例如使用 Visual Studio) 环境下,通常不需要手动添加这个选项,因为链接器会自动处理。
错误处理
正如示例 4 所示,处理无效输入(如负数)是一个好习惯。

(图片来源网络,侵删)
-
检查
errno- 在调用
sqrt之前,将errno设为 0。 - 调用之后,检查
errno的值,如果它被设置为EDOM(定义在<errno.h>中),就意味着发生了域错误(比如对负数开方)。
- 在调用
-
检查返回值
sqrt的返回值是double,你可以使用isnan()函数(来自<math.h>)来检查结果是否为 "NaN"。- 这种方法更直观,因为它直接检查了函数的输出。
使用 isnan 的示例:
#include <stdio.h>
#include <math.h>
int main() {
double number = -16.0;
double result = sqrt(number);
if (isnan(result)) {
printf("Error: The result is NaN (Not a Number).\n");
} else {
printf("The square root is: %f\n", result);
}
return 0;
}
| 要点 | 说明 |
|---|---|
| 头文件 | 必须包含 #include <math.h> |
| 函数原型 | double sqrt(double x); |
| 参数 | x 必须为非负数 (x >= 0) |
| 返回值 | 返回 double 类型的平方根;若 x 为负,返回 NaN |
| 编译 | 在 Linux/macOS 下,编译时需使用 -lm 选项链接数学库 |
| 错误处理 | 检查 errno 或使用 isnan() 函数来处理无效输入 |
记住这些要点,你就可以在 C 语言中正确、安全地使用 sqrt 函数了。
