C语言中库函数math的常见用法

在C语言中,math.h 头文件包含了用于执行数学运算的函数。以下是一些 math.h 库中常见函数的用法示例:

1.计算平方根
cpp 复制代码
#include <stdio.h>
#include <math.h>

int main() {
    double number = 25.0;
    double sqrtValue = sqrt(number);
    printf("The square root of %f is %f\n", number, sqrtValue);
    return 0;
}
2.计算绝对值
cpp 复制代码
#include <stdio.h>
#include <math.h>

int main() {
    double number = -10.5;
    double absValue = fabs(number);
    printf("The absolute value of %f is %f\n", number, absValue);
    return 0;
}
3.计算幂
cpp 复制代码
#include <stdio.h>
#include <math.h>

int main() {
    double base = 2.0;
    double exponent = 3.0;
    double power = pow(base, exponent);
    printf("%f raised to the power of %f is %f\n", base, exponent, power);
    return 0;
}
4.计算最大值和最小值
cpp 复制代码
#include <stdio.h>
#include <math.h>

int main() {
    double a = 10.5;
    double b = 20.5;
    double max = fmax(a, b);
    double min = fmin(a, b);
    printf("The maximum of %f and %f is %f\n", a, b, max);
    printf("The minimum of %f and %f is %f\n", a, b, min);
    return 0;
}
5.计算正弦、余弦和正切
cpp 复制代码
#include <stdio.h>
#include <math.h>

int main() {
    double angle = 45.0; // in degrees
    double sinValue = sin(angle * (M_PI / 180.0));
    double cosValue = cos(angle * (M_PI / 180.0));
    double tanValue = tan(angle * (M_PI / 180.0));
    printf("The sine of %f degrees is %f\n", angle, sinValue);
    printf("The cosine of %f degrees is %f\n", angle, cosValue);
    printf("The tangent of %f degrees is %f\n", angle, tanValue);
    return 0;
}
6.计算对数
cpp 复制代码
#include <stdio.h>
#include <math.h>

int main() {
    double number = 10.0;
    double logValue = log(number);
    printf("The natural logarithm of %f is %f\n", number, logValue);
    return 0;
}
7.计算指数
cpp 复制代码
#include <stdio.h>
#include <math.h>

int main() {
    double base = 2.0;
    double exponent = 3.0;
    double expValue = exp(exponent);
    printf("%f raised to the power of %f is %f\n", base, exponent, expValue);
    return 0;
}

这些函数在处理数学计算时非常有用,它们在 math.h 头文件中定义,并且可以直接在C语言程序中使用。记得在使用这些函数时包含 math.h 头文件。

相关推荐
星辰_mya18 分钟前
PV之系统与并发的核心wu器
java·开发语言·后端·学习·面试·架构师
做时间的朋友。37 分钟前
Java虚拟线程详解:从原理到实战,解锁百万并发新姿势
java·开发语言
一只大袋鼠38 分钟前
MyBatis 从入门到实战(二):代理 Dao 开发与多表关联查询
java·开发语言·数据库·mysql·mybatis
明月醉窗台40 分钟前
Python-opencv批量处理文件夹中图像操作
开发语言·python·opencv
周末也要写八哥42 分钟前
C++实际开发之泛型编程(模版编程)
java·开发语言·c++
好家伙VCC43 分钟前
**发散创新:用 Rust实现游戏日引擎核心模块——从事件驱动到多线程调度的实战
java·开发语言·python·游戏·rust
Dxy12393102161 小时前
Python在图片上画圆形:从入门到实战
开发语言·python
爱编码的小八嘎1 小时前
C语言完美演绎8-4
c语言
桌面运维家1 小时前
IDV云桌面vDisk机房部署方案模板特性解析
java·开发语言·devops
CS_Zero1 小时前
无人机路径规划算法——EGO-planner建模总结—— EGO-planner 论文笔记(一)
论文阅读·算法·无人机