方法1:rand(NULL)函数
代码:
#include<iostream>
using namespace std;
void main(NULL)
{
cout << rand(NULL);
}
运行结果:
41
不过,只要你运行多次代码,你会发现输出的都是41.
方法2:方法1改进版
#include <cstdlib>
#include <ctime>
#include <iostream>
#include<windows.h>
using namespace std;
const int maxs=100;
int main()
{
for (int i=0; i<=10; ++i)
{
srand(time(NULL));
Sleep(1000);
cout<<rand()%maxs<<endl;
}
return 0;
}
注意,这里的sleep很重要,不要试图删掉它!否则就不随机了
C++随机数生成技巧
4157





