C语言随机数函数使用全解析

随机数rand、srand、time

rand函数的使用

rand() 生成伪随机数,头文件是<stdlib.h>

它返回一个范围在 0RAND_MAX(通常为 32767)之间的整数

直接调用 rand() 会生成相同的随机数序列,因为没有设置随机种子。

不适合用于加密等安全场景

c 复制代码
#include <stdio.h>
#include <stdlib.h>

int main() {
    for (int i = 0; i < 5; i++) {
        printf("%d\n", rand());
    }
    return 0;
}

srand函数的使用

srand() 用于设置 rand() 的随机种子,确保每次程序运行时生成不同的随机数序列

通常用 time(NULL) 作为种子,因为时间戳是动态变化的。

多次调用 srand() 可能导致随机性降低。通常只需在程序启动时调用一次。

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand(time(NULL)); // 设置随机种子
    for (int i = 0; i < 5; i++) {
        printf("%d\n", rand());
    }
    return 0;
}

time函数的使用

time() 是时间戳函数,位于 <time.h> 头文件中。传入 NULL 会返回当前系统时间的秒数(从1970年1月1日算起),常用于配合 srand() 生成随机种子。

c 复制代码
#include <stdio.h>
#include <time.h>

int main() {
    time_t current_time = time(NULL);
    printf("Current timestamp: %ld\n", current_time);
    return 0;
}

生成指定范围的随机数

通过取模和加法运算,可以将 rand() 的结果限制在特定范围内

生成 [a, b] 范围内的随机数:

c 复制代码
int random_num = a + rand() % (b - a + 1);

生成0~99之间的随机数:

cpp 复制代码
rand() % 100;

生成1~100之间的随机数

cpp 复制代码
rand() % 100+1;

生成100~200之间的随机数

cpp 复制代码
rand() % 200-100+1;

示例:生成 1100 的随机数:

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand(time(NULL));
    for (int i = 0; i < 5; i++) {
        int num = 1 + rand() % 100;
        printf("%d\n", num);
    }
    return 0;
}

猜数字游戏

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void menu() {
	printf("1.猜数字\n");
	printf("2.退出\n");
}

void game() {
	int r = rand() % 100 + 1;
	int num = 0;
	while (1) {
		printf("请输入数字:");
		scanf("%d", &num);
		if (num == r) {
			printf("猜对了\n");
			break;
		}
		else if (num > r) {
			printf("猜大了\n");
		}
		else {
			printf("猜小了\n");
		}
	}
}

int main() {
	//设置随机种子的起始数
	int a = 0;
	srand((unsigned int)time(NULL));

	do {
		menu();
		printf("请选择菜单:");
		scanf("%d", &a);
		switch (a) {
		case 1:
			game();
			break;
		case 2:
			printf("退出游戏");
			break;
		default:
			printf("请选择:");
			break;
		}
	} while (a);
	return 0;
}
相关推荐
晓蛋1 天前
c语言指的是什么意思
c语言·编译器·编程开发·集成开发环境·程序实例
一隅论数智1 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
傲世仙尊1 天前
目录即文件-Ext文件系统收尾篇
linux·c语言
牵猫散步的鱼儿1 天前
重载、重写(覆盖)、重定义区别
c语言
phltxy1 天前
C 语言指针:从内存地址到灵活的数据访问
c语言
phltxy1 天前
C 语言中的数据存储:从类型到二进制位
c语言
深圳老胡1 天前
STM32F407 控制 L6470 步进电机驱动 —— 控制过程简介
笔记·stm32·单片机·嵌入式硬件·代码规范
Because_of_Her11 天前
并查集-听课笔记
笔记·算法·并查集
彧azz1 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
陈卫军老师1 天前
陈卫军:把口味写在一张纸上,店才稳得住
经验分享·笔记·流量运营