C++的math函数如何用

2023-05-21,

今天小编给大家分享一下C++的math函数如何用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

包含头文件

#include<cmath>

1、fabs(double x)

对double型变量取绝对值

#include<iostream>
using namespace std;
#include<cmath>
int main()
{
    double d=-3.14;
    printf("%.2f\n",fabs(d));
    return 0;
}

2、floor(double x)ceil(double x)

用于double型变量,返回类型也为double

向下取整:floor

向上取整:ceil

#include<iostream>
using namespace std;
#include<cmath>
int main()
{
    double d1=-3.14;
    double d2=3.14;
    printf("%.0f  %.0f\n",floor(d1),ceil(d1));
    printf("%.0f  %.0f\n",floor(d2),ceil(d2));
    return 0;
}

-4 -3

3 4

3、pow(double x,double n)

返回x的n次方

#include<iostream>
using namespace std;
#include<cmath>
int main()
{
    double d=pow(2.0,3.0);
    printf("%f\n",d);
    return 0;
}

8.000000

4、sqrt(double x)

返回double型变量的算术平方根

#include<iostream>
using namespace std;
#include<cmath>
int main()
{
    double d=sqrt(3.0);
    printf("%f\n",d);
    return 0;
}

5、log(double x)

返回以自然对数e为底的对数

#include<iostream>
using namespace std;
#include<cmath>
int main()
{
    double d=log(exp(1));//exp(1)表示e
    printf("%f\n",d);
    double d1=log10(10.0);
    printf("%f\n",d1);
    double d2=log2(2);
    printf("%f\n",d2);
    double d3=log1p(10);//更精确
    printf("%f\n",d3);
    double d4=log(10);
    printf("%f\n",d4);
    return 0;
}

1.000000

1.000000

1.000000

2.397895

2.302585

6、sin(double x)cos(double x) tan(double x)

参数要求是弧度制

也有对应的反函数

#include<iostream>
using namespace std;
#include<cmath>
const double PI=acos(-1.0);//因为cos(pi)=-1
int main()
{
    double d=sin(PI/4);
    printf("%f\n",d);
    double d1=cos(PI/4);
    printf("%f\n",d1);
    double d2=tan(PI/4);
    printf("%f\n",d2);
    double d3=asin(1);
    printf("%f\n",d3);
    double d4=atan(1);
    printf("%f\n",d4);
    return 0;
}

7、round(double x)

将double型变量四舍五入取整,返回也是double

以上就是“C++的math函数如何用”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注本站行业资讯频道。

《C++的math函数如何用.doc》

下载本文的Word格式文档,以方便收藏与打印。