在算法竞赛中,常常需要用生成随机数的办法来产生测试数据,调试程序。用到的函数有rand(),srand(),time()。
(1)rand()
rand()在头文件<cstdlib>中,可以产生0~2147483647的随机数。如果需要某个范围的数,只需要取余即可。
for(int i = 0; i < 10; i++)
{
cout << i << " : ";
cout << rand() << endl;
}
//生成0~9的随机数
for(int i = 0; i < 10; i++)
{
cout << i << " : ";
cout << rand()%10 << endl;
}
(2)srand(), rand(), time()
多次试验会发现,rand()产生的随机数是固定的,这是因为没有设置随机数种子,每次都生成随机数种子1,所以产生的随机数是固定的,解决办法是让随机数种子随时间变化
srand(time(0));
for(int i = 0; i < 10; i++)
{
cout << i << " : ";
cout << rand()%10 << endl;
}