C 标准库 - <math.h>学习笔记
简介
<math.h> 是C标准库中的一个头文件,包含了许多与数学相关的函数。这些函数提供了一些常见的数学运算,如三角函数、指数函数和对数函数等。
常用函数
abs()
abs()
函数用于获取整数的绝对值,其原型如下:
cCopy Codeint abs(int n);
示例代码:
cCopy Code#include <stdio.h>
#include <stdlib.h>
int main() {
int n = -10;
printf("The absolute value of %d is %d\n", n, abs(n));
return 0;
}
输出结果:
Copy CodeThe absolute value of -10 is 10
pow()
pow()
函数用于计算一个数的幂,其原型如下:
cCopy Codedouble pow(double x, double y);
示例代码:
cCopy Code#include <stdio.h>
#include <math.h>
int main() {
double x = 2.0, y = 3.0;
printf("%lf raised to the power of %lf is %lf\n", x, y, pow(x, y));
return 0;
}
输出结果:
Copy Code2.000000 raised to the power of 3.000000 is 8.000000
sin()
sin()
函数用于计算给定角度的正弦值,其原型如下:
cCopy Codedouble sin(double x);
示例代码:
cCopy Code#include <stdio.h>
#include <math.h>
int main() {
double x = 45.0;
printf("The sine of %lf degrees is %lf\n", x, sin(x * M_PI / 180));
return 0;
}
输出结果:
Copy CodeThe sine of 45.000000 degrees is 0.707107
ceil()
ceil()
函数用于获取大于或等于给定小数的最小整数,其原型如下:
cCopy Codedouble ceil(double x);
示例代码:
cCopy Code#include <stdio.h>
#include <math.h>
int main() {
double x = 3.3;
printf("The smallest integer greater than or equal to %lf is %lf\n", x, ceil(x));
return 0;
}
输出结果:
Copy CodeThe smallest integer greater than or equal to 3.300000 is 4.000000
总结
<math.h> 头文件提供了许多常用的数学函数,可以方便地进行数学运算。在使用时,需要注意数据类型、数值范围等问题,以确保正确计算。