C++中常用的数学函数

1. 前言

在日常的刷题中,会经常涉及到数字的运算。C++中提供了较为方便的库函数,可以方便我们快速的解题。

2.库函数
2.1 min

求两个值中最小值的函数。

  • 简单示例
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;


int main(){
	int a,b;
	
	cin >> a >> b;
	int minValue = min(a,b);
	cout << "minValue = "<< minValue;
}
  • 执行结果
    在这里插入图片描述
2.2 max

求两个数中的较大值

  • 简单示例
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;


int main(){
	int a,b;
	
	cin >> a >> b;
	int maxValue = max(a,b);
	cout << "maxValue = "<< maxValue;
}
  • 执行结果
    在这里插入图片描述
2.3 floor

向下取整函数

2.4 round

四舍五入函数

  • 简单示例
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;


int main(){
	double a = 2.6;
	int floorA = floor(a);	
	int roundA = round(a);
	cout << "floorA = "<< floorA <<"\n";	
	cout << "roundA = "<< roundA <<"\n";
}
  • 执行结果
    在这里插入图片描述
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐