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 头文件。

相关推荐
蒋星熠2 分钟前
中间件架构设计与实践:构建高性能分布式系统的核心基石
开发语言·数据库·分布式·python·中间件·性能优化·硬件工程
枫叶丹43 分钟前
【Qt开发】显示类控件(二)-> QLCDNumber
开发语言·qt
Flash.kkl6 分钟前
优先算法——专题十一:字符串
算法
励志不掉头发的内向程序员37 分钟前
STL库——AVL树
开发语言·c++·学习
晨非辰3 小时前
#C语言——刷题攻略:牛客编程入门训练(十一):攻克 循环控制(三),轻松拿捏!
c语言·开发语言·经验分享·学习·visual studio
嫣语岁月4 小时前
【BMS电池管理】基于BQ76920与STM32的BMS设计开发
c语言·vscode·stm32·单片机·嵌入式硬件
励志码农5 小时前
JavaWeb 30 天入门:第二十三天 —— 监听器(Listener)
java·开发语言·spring boot·学习·servlet
天高云淡ylz5 小时前
子网掩码的隐形陷阱:为何能ping通却无法HTTPS访问
开发语言·php
汉克老师7 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(5、机甲战士)
c++·算法·蓝桥杯·01背包·蓝桥杯c++·c++蓝桥杯
希望20177 小时前
Golang Panic & Throw & Map/Channel 并发笔记
开发语言·golang