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

相关推荐
yufei-coder6 分钟前
C#基础语法
开发语言·c#·.net
长天一色6 分钟前
【ECMAScript 从入门到进阶教程】第三部分:高级主题(高级函数与范式,元编程,正则表达式,性能优化)
服务器·开发语言·前端·javascript·性能优化·ecmascript
_.Switch17 分钟前
Python机器学习模型的部署与维护:版本管理、监控与更新策略
开发语言·人工智能·python·算法·机器学习
醉颜凉20 分钟前
银河麒麟桌面操作系统修改默认Shell为Bash
运维·服务器·开发语言·bash·kylin·国产化·银河麒麟操作系统
NiNg_1_23426 分钟前
Vue3 Pinia持久化存储
开发语言·javascript·ecmascript
带带老表学爬虫34 分钟前
java数据类型转换和注释
java·开发语言
qianbo_insist37 分钟前
simple c++ 无锁队列
开发语言·c++
BigYe程普1 小时前
我开发了一个出海全栈SaaS工具,还写了一套全栈开发教程
开发语言·前端·chrome·chatgpt·reactjs·个人开发
彭于晏6891 小时前
Android广播
android·java·开发语言
弱冠少年1 小时前
websockets库使用(基于Python)
开发语言·python·numpy