11.C++程序中的常用函数

我们将程序中反复执行的代码封装到一个代码块中,这个代码块就被称为函数,它类似于数学中的函数,在C++程序中,有许多由编译器定义好的函数,供大家使用。下面就简单说一下,C++中常用的函数。

1.sizeof

sizeof函数用于获取数据的类型或者是变量占多少内存,

#include <iostream>
using namespace std;
int main() {

	int num = 255;

	cout << "int:      " << sizeof(int) << endl;    //int:      4
	cout << "int:      " << sizeof(num) << endl;    //int:      4
	cout << "float:    " << sizeof(float) << endl;  //float:    4
	cout << "bool:     " << sizeof(bool) << endl;   //bool:     1
	cout << "char:     " << sizeof(char) << endl;   //char:     1
	cout << "short:    " << sizeof(short) << endl;  //short:    2

	cout << "long:     " << sizeof(long) << endl;     //long:     8
	cout << "long long:" << sizeof(long long) << endl; //long long:8
	cout << "double:   " << sizeof(double) << endl;   //double:   8

	cout << "string:   " << sizeof(string) << endl;   //string:   32



}

执行结果:

2.取最大值(max),最小值(min)函数

#include <iostream>
using namespace std;
int main() {

	cout << max(100.1, 111.1);  //111.1
	cout << endl;
	cout << max(233, -9);    //233
	cout << endl;
	cout << min(2.9, 0.2); //0.2
	cout << endl;
	cout << min(-100.0, -0.2); //-100
}

 

从上面可以看出来,max函数,是取两个数中的大值,min是取两个数中的小值。

3. 取整( 四舍五入取整round, 向上取整ceil, 向下取整floor,向0取整 trunc)

#include <iostream>
#include <math.h> //需要包含头文件
using namespace std;

int main() {

	float num = 100.65;
	cout << "ceil== " << ceil(num) << endl; //向上取整		 
	cout << "floor== " << floor(num) << endl; //向下取整
	cout << "round== " << round(num) << endl; //四舍五入取整
	cout << "trunc== " << trunc(num) << endl; //向0方向取整


}

4.取绝对值(整数abs,小数fabs)

#include <iostream>
#include <math.h> //需要包含头文件
using namespace std;

int main() {

	float num = -100.65;
	cout << "fabs== " << fabs(num) << endl; //小数取绝对值
	int i=-10;	 
	cout << "abs== " << abs(i) << endl; //整数取绝对值


}

以上这些是C++的标准函数,还有一些是其它库私有的,比如 最大公因数gcd,最小公倍数lcm等就不是C++的标准库函数,只能在一些特定的平台下使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值