• C++
  • 一级常用输出格式与实用函数大全

  • @ 2026-2-2 14:22:04


🌟 常用输出格式与实用函数大全(🔥 一级高频补充)

🎯(保留小数 / 四舍五入 / 数学函数 / 字符处理 必考)


⭐ 一、保留小数输出(超级高频考点)


✅ 方法一:fixed + setprecision(⭐推荐)

#include<bits/stdc++.h>
using namespace std;

int main()
{
    double x = 3.1415926;

    cout << fixed << setprecision(2) << x;

    return 0;
}

输出:

3.14

⭐ 写法模板(必须会背)

cout << fixed << setprecision(保留位数) << 变量;

🎯 例题

保留3位小数

cout << fixed << setprecision(3) << a;


# ⭐ 二、四舍五入方法


✅ round() 四舍五入

cout << round(3.6);   // 4
cout << round(3.4);   // 3

✅ 手动四舍五入技巧(竞赛常用)

int ans = (int)(x + 0.5);


# ⭐ 三、常用数学函数(一级必须认识)


⭐ 需要头文件

#include<cmath>

(万能头已包含)


⭐ 常见函数表

函数 作用 示例
abs(x) 绝对值 abs(-5)=5
sqrt(x) 开根号 sqrt(9)=3
pow(a,b) 次方 pow(2,3)=8
round(x) 四舍五入 round(3.6)=4
ceil(x) 向上取整 ceil(3.1)=4
floor(x) 向下取整 floor(3.9)=3

🎯 示例

cout << abs(-10);
cout << sqrt(16);
cout << pow(2,5);


# ⭐ 四、字符与ASCII常用技巧(🔥 必考)


⭐ 判断数字字符

if(c >= '0' && c <= '9')

⭐ 判断字母

if(c >= 'a' && c <= 'z')

⭐ 大小写转换

c = c + 32;  // 大写→小写
c = c - 32;  // 小写→大写

⭐ 字符转数字

int x = c - '0';

⭐ 数字转字符

char c = x + '0';


# ⭐ 五、字符串 string 常用方法(一级开始涉及)


⭐ 定义

string s = "hello";

⭐ 常用操作

长度

s.size()

访问字符

s[0]

拼接

s = s + "world";

输入整行

getline(cin, s);


# ⭐ 六、swap 交换变量(竞赛超常用)


int a=3,b=5;
swap(a,b);

结果:

a=5 b=3


# ⭐ 七、max / min 最值函数


cout << max(a,b);
cout << min(a,b);


# ⭐ 八、常用技巧小模板(直接背)


⭐ 保留2位小数

cout << fixed << setprecision(2) << x;

⭐ 求绝对值

abs(x);

⭐ 开平方

sqrt(x);

⭐ 判断数字字符

if(c>='0'&&c<='9')

⭐ 交换两个数

swap(a,b);


# # 🎯 一级考试函数记忆口诀

保留小数 fixed
四舍五入 round
绝对值 abs
开方 sqrt
次方 pow
最大最小 max min
交换 swap

0 条评论

目前还没有评论...