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;
}
相关推荐
「QT(C++)开发工程师」9 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天9 小时前
0 初识C++
开发语言·c++
FfHUCisI10 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI10 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
lemon_sjdk11 小时前
ObjectProperty
java·开发语言·算法
大模型码小白11 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
hh95011 小时前
Agent Plan x DeepSeek Harness:Agent 供应链安全与第三方插件审计
java·开发语言·安全·agent plan·adg成都社区·adg社区
「QT(C++)开发工程师」11 小时前
C++ std::move 详解
开发语言·c++
matlab代码11 小时前
基于matlab的玉米种子计数设计(GUI界面)【源码58期】
开发语言·matlab