随机数
- 伪随机数的实现:
伪随机数:计算机执行程序每次产生的随机数都是相同的;
#include<iostream>
#include<stdlib.h>//引入含rand()的头文件;
using namespace std;
int main(){
int a ;
rand()%100;//生成0~99的随机数;
a=rand()%100;
cout<<a<<endl;
system("pause");
return 0;
}
运行结果:
原因:未设定随机数种子,系统默认随机数种子为1。
- 利用系统时间生成随机数(添加随机数种子)
```cpp
#include<iostream>
#include<stdlib.h>//引入含rand()的头文件;
#include<time.h> //引入时间的头文件;
using namespace std;
int main(){
srand((unsigned int)time(NULL));//随机数种子,利用系统时间在变化;
int a ;
rand()%100;//生成0~99的随机数;
a=rand()%100;
cout<<a<<endl;//打印生成的随机数。
system("pause");
return 0;
}
运行结果: