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;
}
相关推荐
感哥6 小时前
C++ 多态
c++
沐怡旸13 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River41616 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥18 小时前
C++ std::set
c++
侃侃_天下19 小时前
最终的信号类
开发语言·c++·算法
博笙困了19 小时前
AcWing学习——差分
c++·算法
echoarts19 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix19 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
青草地溪水旁20 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁20 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式