C风格的随机数
srand和rand
srand
——产生随机数种子
rand()%n
——产生0~n随机数
rand()%n+1
产生1~n随机数
/* rand example: guess the number */
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
int iSecret, iGuess;
/* initialize random seed: */
srand (time(NULL));
/* generate secret number between 1 and 10: */
iSecret = rand() % 10 + 1;
do {
printf ("Guess the number (1 to 10): ");
scanf ("%d",&iGuess);
if (iSecret<iGuess) puts ("The secret number is lower");
else if (iSecret>iGuess) puts ("The secret number is higher");
} while (iSecret!=iGuess);
puts ("Congratulations!");
return 0;
}
全局随机数种子——避免多次调用 srand 引起 rand 产生同一随机数
这套伪随机有个问题,如果调用的时间间隔不是以秒为数量级 每次出来的随机数都相同。调用速度太快,使得每次srand
初始化随机数种子。
auto rdm = [](){
srand(time(0));
for(int i = 0;i<5;++i){
cout << rand()%10<< '\t';}
cout<<'\n';};
for(int j = 0;j<5;++j)
rdm();
/*输出举例
9 0 1 6 7
9 0 1 6 7