在c++中生成随机数主要用到三个函数:1.rand() 2.srand() 3.time
1.rand()
如果只是随机生成一个数或者几个数,而不限定范围 那么直接用rand()即可
#include <iostream>
using namespace std;
int main() {
/*只用rand()可以生成一个或几个随机数,此时没有范围的限制,
但是由于一台电脑的缘故,所以每次运行生成相同的随机数*/
int num = rand();
cout << num << endl;
for (int i = 0; i < 10; i++)
{
cout << rand() << endl;
}
system("pause");
return 0;
}
如果是限制范围(0-9),则需要rand() % 10
若是需要1-10,则rand() % 10 +1;
rand() % 11 表示:0-10;
#include <iostream>
using namespace std;
int main() {
/*只用rand()可以生成一个或几个随机数,此时没有范围的限制,
但是由于一台电脑的缘故,所以每次运行生成相同的随机数*/
int num = rand() % 10;
cout << num << endl;
for (int i = 0; i < 10; i++)
{
cout << rand() % 10 << " ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << (rand() % 10 + 1) << " ";
}
system("pause");
return 0;
}
2.srand()
我们通过多次运行发现,该程序虽然生成了10个随机数,但是这个10个随机数是固定的,也就是说并不随着时间的变化而变化。
这与srand()函数有关。srand()用来设置rand()产生随机数时的随机数种子。在调用rand()函数产生随机数前,必须先利用srand()设好随机数种子(seed), 如果未设随机数种子, rand()在调用时会自动设随机数种子为1。
srand()函数定义 : void srand (unsigned int seed); 其中一般可以用 time(NULL)来当做seed
但在此之前需要添加一个#include <ctime>的头文件
#include <iostream>
#include <ctime>
using namespace std;
int main() {
/*只用rand()可以生成一个或几个随机数,此时没有范围的限制,
但是由于一台电脑的缘故,所以每次运行生成相同的随机数*/
srand((int unsigned)time(NULL));
int num = rand() % 10;
cout << num << endl;
for (int i = 0; i < 10; i++)
{
cout << rand() % 10 << " ";
}
cout << endl;
for (int i = 0; i < 10; i++)
{
cout << (rand() % 10 + 1) << " ";
}
system("pause");
return 0;
}