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

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

1.sizeof

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

cpp 复制代码
#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)函数

cpp 复制代码
#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是取两个数中的小值。

  1. 取整( 四舍五入取整round, 向上取整ceil, 向下取整floor,向0取整 trunc)
cpp 复制代码
#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)

cpp 复制代码
#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++的标准库函数,只能在一些特定的平台下使用。

相关推荐
夏末秋也凉20 分钟前
力扣-贪心-376 摆动序列
算法·leetcode
奔跑吧邓邓子20 分钟前
【Python爬虫(34)】Python多进程编程:开启高效并行世界的钥匙
开发语言·爬虫·python·多进程
刃神太酷啦1 小时前
堆和priority_queue
数据结构·c++·蓝桥杯c++组
Heris991 小时前
2.22 c++练习【operator运算符重载、封装消息队列、封装信号灯集】
开发语言·c++
----云烟----1 小时前
C/C++ 中 volatile 关键字详解
c语言·开发语言·c++
Orange--Lin1 小时前
【用deepseek和chatgpt做算法竞赛】——还得DeepSeek来 -Minimum Cost Trees_5
人工智能·算法·chatgpt
01_1 小时前
力扣hot100 ——搜索二维矩阵 || m+n复杂度优化解法
算法·leetcode·矩阵
SylviaW081 小时前
python-leetcode 35.二叉树的中序遍历
算法·leetcode·职场和发展
篮l球场1 小时前
LeetCodehot 力扣热题100
算法·leetcode·职场和发展