一、头文件
C/C++产生随机数,为了使随机数更加准确,这边使用的是srand和rand的配合使用
产生随机数的头文件:#include <time.h>
二、产生100以内的随机数
//这个产生的是100以内的随机数
srand((int)time(NULL));
int b = rand() % 100;
cout << "b =" << b << endl;
三、产生-50~49之间的随机数
//这个产生的是-50~49之间的随机数
srand((int)time(NULL));
int a = rand() % 100 - 50;
cout << "a =" << a << endl;
四、产生多个随机数
//产生多个随机数,这边是5个随机数,范围是-50到-49之间的数
srand((int)time(NULL));
for (int i = 0; i < 5;i++)
{
int a = rand() % 100 - 50;
cout << "a =" << a << endl;
}
五、总结一般特点:
一般特点:rand() % (b-a+1)+ a ; 就表示 a~b 之间的一个随机整数
//一般特点:rand() % (b-a+1)+ a ; 就表示 a~b 之间的一个随机整数
//这边表示的依然是-50~49之间的随机数
srand((int)time(NULL));
for (int j = 0; j < 50;j++)
{
int i = rand() % (49 - (-50) + 1) - 50;
cout << "i = " << i << endl;
}