C++:随机数

阅读 86

2022-04-24

Rand()%100; //得到一个0~99的随机数

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
	int a = rand() % 100;
	cout << "随机数a=" << a << endl;
	
	system("pause");
	return 0;
}

但是实际中 不管运行多少次,得到的随机数都是不变的

在这里插入图片描述

添加随机数种子 作用利用系统当前的时间生成的随机数
Srand((unsigned int)time(null));//根据系统时间生成一个随机数
//需要加入头文件 #include

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
	srand((unsigned int)time(NULL));//根据系统时间生成一个随机数
	int a = rand() % 100;
	cout << "随机数a=" << a << endl;

	system("pause");
	return 0;
}

加入srand((unsigned int)time(NULL));//根据系统时间生成一个随机数每次运行的结果都是随机的

精彩评论(0)

0 0 举报