c++常用的 math 函数讲解

版权声明:置顶文章如需转载请联系作者 https://blog.csdn.net/Bonstoppo/article/details/82056635

谈不上讲解,算是一点小的总结吧,把近期遇到的一些常用的函数进行一个归类。

1.绝对值函数 fabs ( double x ) 与 abs ( int x )

fabs( double x) 主要是用来做绝对值运算的,fabs用来解决double / float 类型的数据,abs则是int类型。

#include<iostream>
#include<cmath>
using namespace std;
int main() {
	float x = -12.3;
	int y = -24;
	printf("%.2f\n" , fabs(x));
	printf("%d" , abs(y)); 
	return 0;
} 

 

2.取整函数 floor(double x) 与 ceil(double x)

向下取整的意思便是,该数值往数轴小的方向走 ; 与此相反,向上取整,往该数值数轴大的方向走。floor (地板)  ceil (天花板)

#include<iostream>
#include<cmath>
using namespace std;
int main() {
	double d = -5.2;
	printf("%.0f\n" , floor(d)); //Answer is -6// 
	printf("%.0f" , ceil(d)); 	//Answer is -5 // 
	return 0;
} 

3.指数函数 x ^y pow( double x , double y )

注意次序。x是底,y 是幂。

#include<iostream>
#include<math.h>
using namespace std;
int main() {
	double x = 3.1 ; 
	double y = 2.0 ;
	printf("%lf" , pow(x , y));//The Answer is 9.61 //
	return 0;
} 

4.sqrt ( double x )开方函数

当如果得到 int 数值的时候会直接截取,不会四舍五入。

#include<iostream>
#include<math.h>
using namespace std;
int main() {
	double x = sqrt (3.0);
	printf("%lf" , x);
	return 0;
} 

5.log( double x) 取对数函数

这个地方有点问题。这个 x 是什么,是底数?还是什么?

#include<iostream>
#include<math.h>
using namespace std;
int main() {
	double x = 3.1 ; 
	printf("%lf" , log( x ));//The Answer is 1.132 //
	return 0;
} 

6.round( double x ) 四舍五入取整函数

这个函数只能是 double 变成 int ,并且只能是对整数位进行修正。

#include<iostream>
#include<math.h>
using namespace std;
int main() {
	double x = round(3.55); 
	printf("%d" , (int)x);//The Answer is 4 //
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/Bonstoppo/article/details/82056635