Level 1 · Day 8

常用库函数速查

用别人写好的轮子。用库函数前,先 #include 对应头文件(引入原型)。

一、互动演示:字符函数 cctype

点一个字符,看各个 is...() 函数返回真(1)还是假(0)。

二、三大常用头文件

<cmath> 数学
sqrt(x)平方根
pow(x,y)x 的 y 次方
abs(x)绝对值
ceil / floor / round上取整 / 下取整 / 四舍五入
<algorithm> 工具
max(x,y)较大者
min(x,y)较小者
swap(a,b)交换两值
sort(...)排序

三、参考代码

#include <iostream>
#include <cmath>
#include <cctype>
#include <algorithm>
using namespace std;

int main() {
    cout << sqrt(16) << endl;     // 4
    cout << max(3, 9) << endl;     // 9

    char c = 'A';
    if (isupper(c)) c = tolower(c);   // 转成 'a'
    cout << c << endl;

    int x = 1, y = 2;
    swap(x, y);                  // 一行交换
    cout << x << " " << y;        // 2 1
    return 0;
}

记不住就查手册:cplusplus.com/reference。会查会用,比死记强。