C++的随机数操作

首先想到的肯定是rand()函数,但是这个有点问题

引入头文件<stdlib.h>

如果不引入种子,它的随机数不是随机数,是固定的一串数字

srand()函数,产生随机的种子

示例:

产生0-99的随机数

cpp 复制代码
#include<stdlib.h>
#include<iostream>
#include<ctime>
using namespace std;
int main(){
	srand((int)time(NULL));
	int num=rand()%100;
	cout<<num<<endl;
	return 0;
}

产生1-100

cpp 复制代码
#include<stdlib.h>
#include<iostream>
#include<ctime>
using namespace std;
int main(){
	srand((int)time(NULL));
	int num=rand()%100+1;
	cout<<num<<endl;
	return 0;
}
相关推荐
paeamecium几秒前
【PAT甲级真题】- All Roads Lead to Rome (30)
数据结构·c++·算法·pat考试·pat
好家伙VCC5 分钟前
**发散创新:基于Rust的轻量级权限管理库设计与开源许可证实践**在现代分布式系统中,**权限控制(RBAC
java·开发语言·python·rust·开源
xiaoshuaishuai811 分钟前
C# 方言识别
开发语言·windows·c#
John.Lewis17 分钟前
C++进阶(6)C++11(2)
开发语言·c++·笔记
@atweiwei18 分钟前
用 Rust 构建agent的 LLM 应用的高性能框架
开发语言·后端·rust·langchain·eclipse·llm·agent
skilllite作者21 分钟前
Spec + Task 作为「开发协议层」:Rust 大模型辅助的标准化、harness 化与可回滚
开发语言·人工智能·后端·安全·架构·rust·rust沙箱
Dxy123931021621 分钟前
Python序列标注模型上下文纠错详解
开发语言·python
孙鹏宇.22 分钟前
左值右值.
java·开发语言
风吹迎面入袖凉27 分钟前
【Redis】Redisson分布式锁原理
java·服务器·开发语言
A.A呐27 分钟前
【QT第五章】系统相关
开发语言·qt