C: 常用标准库

🗓 最后更新:2026-11-30👤 作者:Gray✓ 审校:Alex🏷 分类:C 教程

标准库就像工具箱——你不需要自己造锤子螺丝刀,拿来用就行。了解每个工具的用途,才能选对工具。

本节涉及手册条目: rand() srand atoi strtol malloc calloc realloc free char rand

1. math.h 数学运算

使用数学函数需要包含头文件并链接数学库:

C
// 预处理指令
#include <math.h>

编译时加 -lm 选项:gcc program.c -lm。

(1) 常用数学函数

函数 功能 示例
fabs(x) 绝对值 fabs(-3.5) → 3.5
sqrt(x) 平方根 sqrt(16.0) → 4.0
pow(x, y) x的y次幂 pow(2.0, 10.0) → 1024.0
ceil(x) 向上取整 ceil(3.2) → 4.0
floor(x) 向下取整 floor(3.8) → 3.0
round(x) 四舍五入 round(3.5) → 4.0
fmod(x, y) 浮点取余 fmod(7.5, 2.5) → 0.0
log(x) 自然对数 log(2.718) → 1.0
log10(x) 常用对数 log10(100.0) → 2.0
sin(x) 正弦 sin(3.14/2) → 1.0
cos(x) 余弦 cos(0.0) → 1.0
tan(x) 正切 tan(0.0) → 0.0
⚠️ 三角函数的参数是弧度,不是角度!角度转弧度:rad = deg * 3.14159265 / 180.0。

▶ 示例

计算两点之间的距离:

▶ 试一试
TEXT
距离: 5.00

2. stdlib.h 通用工具

(1) 随机数

C
// 函数定义
int rand(void);
// 函数定义
void srand(unsigned int seed);

rand() 返回 0 到 RAND_MAX 之间的伪随机整数。不调用 srand 时,每次运行程序产生的随机数序列相同。

C
// 预处理指令
#include <stdio.h>
// 预处理指令
#include <stdlib.h>
// 预处理指令
#include <time.h>

// 函数定义
int main(void) {
    srand((unsigned int)time(NULL));

    // for 循环
    for (int i = 0; i < 5; i++) {
        // 输入输出操作
        printf("%d ", rand());
    }
    // 输入输出操作
    printf("\n");

    // for 循环
    for (int i = 0; i < 5; i++) {
        // 输入输出操作
        printf("%d ", rand() % 100);
    }
    // 输入输出操作
    printf("\n");

    // 返回结果
    return 0;
}
TEXT
1804289383 846930886 1681692777 1714636915 1957747793
83 86 77 15 93
⚠️ rand() % N 在大多数实现中随机性不够好,低位可能呈规律分布。对随机性要求高的场景应使用更高级的随机数生成器。

(2) 类型转换

函数 功能
atoi(str) 字符串转 int
atol(str) 字符串转 long
atof(str) 字符串转 double
strtol(str, &end, base) 字符串转 long(指定进制)
strtod(str, &end) 字符串转 double(带错误检测)
C
// 预处理指令
#include <stdio.h>
// 预处理指令
#include <stdlib.h>

// 函数定义
int main(void) {
    // 变量声明
    int a = atoi("42");
    // 变量声明
    double b = atof("3.14");
    // 变量声明
    long c = strtol("0xFF", NULL, 16);

    // 输入输出操作
    printf("a = %d\n", a);
    // 输入输出操作
    printf("b = %.2f\n", b);
    // 输入输出操作
    printf("c = %ld\n", c);

    // 变量声明
    char *end;
    // 变量声明
    long d = strtol("123abc", &end, 10);
    // 输入输出操作
    printf("d = %ld, 未转换部分: %s\n", d, end);

    // 返回结果
    return 0;
}
TEXT
a = 42
b = 3.14
c = 255
d = 123, 未转换部分: abc
💡 atoi 无法检测错误——输入非法字符串返回 0,和真正的 0 无法区分。建议用 strtol/strtod,通过 end 指针判断是否转换成功。

(3) 动态内存管理

C
// 函数定义
void *malloc(size_t size);
// 函数定义
void *calloc(size_t count, size_t size);
// 函数定义
void *realloc(void *ptr, size_t size);
// 函数定义
void free(void *ptr);
C
// 预处理指令
#include <stdio.h>
// 预处理指令
#include <stdlib.h>

// 函数定义
int main(void) {
    // 变量声明
    int *arr = calloc(5, sizeof(int));
    // 条件判断
    if (arr == NULL) {
        // 返回结果
        return 1;
    }

    // for 循环
    for (int i = 0; i < 5; i++) {
        arr[i] = i * 10;
    }

    // 变量声明
    int *new_arr = realloc(arr, 10 * sizeof(int));
    // 条件判断
    if (new_arr == NULL) {
        // 动态内存操作
        free(arr);
        // 返回结果
        return 1;
    }
    arr = new_arr;

    // for 循环
    for (int i = 5; i < 10; i++) {
        arr[i] = i * 10;
    }

    // for 循环
    for (int i = 0; i < 10; i++) {
        // 输入输出操作
        printf("%d ", arr[i]);
    }
    // 输入输出操作
    printf("\n");

    // 动态内存操作
    free(arr);
    // 返回结果
    return 0;
}
TEXT
0 10 20 30 40 50 60 70 80 90
⚠️ realloc 失败时返回 NULL,但原内存不会被释放!所以必须用临时变量接收 realloc 的返回值,失败时仍可 free 原内存。

(4) 排序与搜索

qsort

C
// 函数定义
void qsort(void *base, size_t count, size_t size,
           int (*compare)(const void *, const void *));

比较函数规则:返回负数表示 a < b,0 表示相等,正数表示 a > b。

C
// 预处理指令
#include <stdio.h>
// 预处理指令
#include <stdlib.h>
// 预处理指令
#include <string.h>

// 函数定义
int cmp_int(const void *a, const void *b) {
    // 返回结果
    return *(const int *)a - *(const int *)b;
}

// 函数定义
int cmp_str(const void *a, const void *b) {
    // 返回结果
    return strcmp(*(const char **)a, *(const char **)b);
}

// 函数定义
int main(void) {
    int nums[] = {42, 17, 8, 95, 3, 61};
    // 变量声明
    int n = sizeof(nums) / sizeof(nums[0]);

    qsort(nums, n, sizeof(int), cmp_int);
    // for 循环
    for (int i = 0; i < n; i++) {
        // 输入输出操作
        printf("%d ", nums[i]);
    }
    // 输入输出操作
    printf("\n");

    const char *names[] = {"Alice", "Bob", "Carol", "赵六"};
    // 变量声明
    int m = sizeof(names) / sizeof(names[0]);

    qsort(names, m, sizeof(char *), cmp_str);
    // for 循环
    for (int i = 0; i < m; i++) {
        // 输入输出操作
        printf("%s ", names[i]);
    }
    // 输入输出操作
    printf("\n");

    // 返回结果
    return 0;
}
TEXT
3 8 17 42 61 95
Alice Bob Carol 赵六

bsearch

C
// 函数定义
void *bsearch(const void *key, const void *base, size_t count,
              size_t size, int (*compare)(const void *, const void *));

在已排序数组中二分查找,找到返回指向元素的指针,未找到返回 NULL。

C
// 预处理指令
#include <stdio.h>
// 预处理指令
#include <stdlib.h>

// 函数定义
int cmp_int(const void *a, const void *b) {
    // 返回结果
    return *(const int *)a - *(const int *)b;
}

// 函数定义
int main(void) {
    int nums[] = {3, 8, 17, 42, 61, 95};
    // 变量声明
    int n = sizeof(nums) / sizeof(nums[0]);

    // 变量声明
    int key = 42;
    // 变量声明
    int *result = bsearch(&key, nums, n, sizeof(int), cmp_int);

    // 条件判断
    if (result != NULL) {
        // 输入输出操作
        printf("找到 %d,下标 %ld\n", key, result - nums);
    } else {
        // 输入输出操作
        printf("未找到 %d\n", key);
    }

    // 返回结果
    return 0;
}
TEXT
找到 42,下标 3

3. time.h 时间处理

(1) 时间函数

函数/类型 功能
time_t 时间类型(通常是从1970-01-01起的秒数)
time(&t) 获取当前时间
clock() 获取程序运行的CPU时钟数
localtime() 转换为本地时间结构体
gmtime() 转换为UTC时间结构体
strftime() 格式化时间字符串
difftime() 计算两个时间的差(秒)

(2) struct tm

C
// 结构体/枚举/联合 定义
struct tm {
    // 变量声明
    int tm_sec;
    // 变量声明
    int tm_min;
    // 变量声明
    int tm_hour;
    // 变量声明
    int tm_mday;
    // 变量声明
    int tm_mon;
    // 变量声明
    int tm_year;
    // 变量声明
    int tm_wday;
    // 变量声明
    int tm_yday;
    // 变量声明
    int tm_isdst;
};

tm_mon 范围 0-11(0=一月),tm_year 是从 1900 年起的年数,tm_wday 中 0 表示周日。

▶ 示例

▶ 试一试
TEXT
当前时间: 2025年03月15日 14:30:22
今天是星期6

(3) 程序计时

C
// 预处理指令
#include <stdio.h>
// 预处理指令
#include <time.h>

// 函数定义
int main(void) {
    clock_t start = clock();

    volatile long sum = 0;
    // for 循环
    for (long i = 0; i < 100000000L; i++) {
        sum += i;
    }

    clock_t end = clock();
    // 变量声明
    double elapsed = (double)(end - start) / CLOCKS_PER_SEC;
    // 输入输出操作
    printf("耗时: %.3f 秒\n", elapsed);

    // 返回结果
    return 0;
}
TEXT
耗时: 0.235 秒
⚠️ clock() 测量的是 CPU 时间,不是墙上时钟时间。如果程序中有 sleep 或等待 I/O,这些时间不计入。需要测量实际经过时间用 difftime。


4. ctype.h 字符处理

函数 判断条件
isalpha(c) 字母
isdigit(c) 数字
isalnum(c) 字母或数字
isupper(c) 大写字母
islower(c) 小写字母
isspace(c) 空白字符(空格、制表、换行等)
ispunct(c) 标点符号
isprint(c) 可打印字符
toupper(c) 转大写
tolower(c) 转小写

这些函数的参数必须是 unsigned char 的值或 EOF。传入负值的 char 是未定义行为。

▶ 示例

统计字符串中字母、数字和其他字符的个数:

▶ 试一试
TEXT
字母: 10, 数字: 3, 其他: 6

5. assert.h 断言

C
// 函数定义
void assert(int expression);

当表达式为假时,程序终止并打印错误信息(文件名、行号、表达式)。在 #include <assert.h> 之前定义 NDEBUG 宏可以禁用所有断言。

C
// 预处理指令
#include <stdio.h>
// 预处理指令
#include <assert.h>

// 函数定义
double safe_divide(double a, double b) {
    assert(b != 0 && "除数不能为零");
    // 返回结果
    return a / b;
}

// 函数定义
int main(void) {
    // 输入输出操作
    printf("10 / 2 = %.1f\n", safe_divide(10.0, 2.0));
    // 输入输出操作
    printf("10 / 0 = %.1f\n", safe_divide(10.0, 0.0));
    // 返回结果
    return 0;
}
TEXT
10 / 2 = 5.0
Assertion failed: b != 0 && "除数不能为零", file main.c, line 5
💡 assert 的字符串字面量会被打印出来,所以 "除数不能为零" 这种写法比注释更有效——断言失败时能直接看到原因。

本节涉及手册条目: rand() srand atoi strtol malloc calloc realloc free char rand

❓ 常见问题

Q C语言怎么用 rand 生成 0 到 100 的随机数?
A rand() % 101 得到 0 到 100,前面先 srand(time(NULL)) 播种。 通用公式是 min + rand() % (max - min + 1),1 到 100 就写 1 + rand() % 100。取模会让低位分布略微不均,对随机性要求高的场景用浮点缩放:(int)((double)rand() / RAND_MAX * 100)。
Q C语言 rand 函数怎么用?
A 包含 <stdlib.h> 后直接调用 rand(),返回 0 到 RAND_MAX 之间的整数。 想让每次运行结果不同,在 main 开头调用一次 srand((unsigned)time(NULL));srand 只调一次,放进循环会导致拿到同一批数。需要可复现的实验结果时反而要用固定种子,比如 srand(42)。
Q srand 和 rand 有什么区别?
A srand 设置随机数种子(起点),rand 按种子生成序列。 种子相同序列就完全相同;不调 srand 等价于 srand(1),所以程序每次运行的输出一模一样。srand 在程序开始时调用一次即可,rand 在需要随机数时反复调用。用 time(NULL) 做种子能保证不同时刻运行结果不同。
Q C语言 qsort 函数怎么用?
A qsort(数组, 元素个数, 单个元素大小, 比较函数),比较函数决定升序还是降序。 例如 qsort(a, n, sizeof(a[0]), cmp_int),比较函数写成 int cmp_int(const void *a, const void *b),内部取 int x = *(const int *)a; 后返回 (x > y) - (x < y)。直接返回 x - y 在数值接近 INT_MIN/INT_MAX 时会溢出。
Q C语言什么时候需要用 math.h?
A 用到 sqrt、pow、sin、fabs、floor 这类数学函数就要包含它。 三角函数参数是弧度不是角度,度转弧度写 deg * PI / 180;M_PI 不是标准宏,自己写 #define PI 3.14159265358979323846 更稳。Linux 下编译还要加 -lm,否则链接时报 undefined reference to 'sqrt'。
Q C语言 time 函数怎么用?
A time(NULL) 返回从 1970-01-01 起的秒数,类型是 time_t,常用来做随机种子或时间戳。 要可读的日期时间,用 localtime(&t) 得到 struct tm *,注意 tm_year 要加 1900、tm_mon 要加 1。格式化输出用 strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", tm)。
Q C语言怎么获取当前时间并格式化输出?
A time 取时间戳,localtime 转结构体,strftime 格式化。 三行就够:time_t t = time(NULL); struct tm *tm = localtime(&t); strftime(buf, sizeof buf, "%Y-%m-%d", tm);。要毫秒级得用平台接口或 clock_gettime,标准 C 的 clock() 返回的是 CPU 时间,不是墙上时间。
Q C语言 assert 函数有什么作用,什么时候该用?
A 开发阶段检查「绝不该发生」的条件,不满足就打印文件名和行号并终止程序。 assert(p != NULL); 比程序默默崩溃更容易定位。它适合查内部逻辑错误(参数为负、状态非法),不适合处理用户输入错误或文件不存在这类正常失败。发布版用 #define NDEBUG 后再包含 <assert.h>,所有断言会被编译掉。

📖 小节

📝 作业

  1. 编写程序,生成 100 个 1-1000 的随机整数,用 qsort 排序后输出最大值和最小值
  2. 编写程序,用 clock() 比较冒泡排序和 qsort 排序 10000 个整数的时间差异
  3. 编写函数,用 ctype.h 的函数实现字符串的大小写转换(输入一个字符串,输出全大写和全小写版本)
Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

内容由 MOTO 审校 · 发现错误?报告给我们

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏