C 语言中的平方根函数383
在 C 语言中,没有内置的平方根函数。但是,我们可以使用数学库中的 sqrt() 函数来计算平方根。
sqrt() 函数声明如下:```c
#include
double sqrt(double x);
```
其中,x 是要计算平方根的数字,sqrt() 返回 x 的平方根。
例如,以下代码计算数字 9 的平方根:```c
#include
#include
int main() {
double x = 9;
double result = sqrt(x);
printf("9 的平方根为:%.2f", result);
return 0;
}
```
输出为:```text
9 的平方根为:3.00
```
sqrt() 函数不仅可以计算正数的平方根,还可以计算负数的平方根。但是,对于负数,sqrt() 函数返回 NaN(非数字),表示结果不是实数。
例如,以下代码计算数字 -9 的平方根:```c
#include
#include
int main() {
double x = -9;
double result = sqrt(x);
printf("-9 的平方根为:%.2f", result);
return 0;
}
```
输出为:```text
-9 的平方根为:nan
```
要检查 sqrt() 函数的返回值是否为 NaN,我们可以使用 isnan() 函数。isnan() 函数声明如下:```c
#include
int isnan(double x);
```
其中,x 是要检查的数字,isnan() 返回 1 表示 x 是 NaN,否则返回 0。
例如,以下代码检查数字 result 是否为 NaN:```c
#include
#include
int main() {
double x = -9;
double result = sqrt(x);
if (isnan(result)) {
printf("%f is NaN", result);
} else {
printf("%f is not NaN", result);
}
return 0;
}
```
输出为:```text
-9.000000 is NaN
```
2025-01-28
上一篇:字符编码与 C 语言乱码输出探究
Java数组元素:从基础到高级操作的深度解析
https://www.shuihudhg.cn/134539.html
PHP Web应用的安全基石:全面解析数据库SQL注入防御
https://www.shuihudhg.cn/134538.html
Python函数入门到进阶:用简洁代码构建高效程序
https://www.shuihudhg.cn/134537.html
PHP中解析与提取代码注释:DocBlock、反射与AST深度探索
https://www.shuihudhg.cn/134536.html
Python深度解析与高效处理.dat文件:从文本到二进制的实战指南
https://www.shuihudhg.cn/134535.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html