随机数
rand() 随机数发生器
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
cout << "this is main()" << endl;
cout << rand() << endl;
return 0;
}
控制随机数范围
[a,b):使用 (rand() % (b-a)) + a
[a,b]:使用 (rand() % (b-a+1)) + a
(a,b]:使用 (rand() % (b-a)) + a + 1
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <string>
using namespace std;
int getRand(int min, int max)
{
return ((rand() % (max-min+1)) + min);
}
int main(int argc, char *argv[])
{
cout << "this is main()" << endl;
cout << getRand(0, 10) << endl;
return 0;
}
srand() 设置随机数种子
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <string>
using namespace std;
int getRand(int min, int max)
{
return ((rand() % (max-min+1)) + min);
}
int main(int argc, char *argv[])
{
cout << "this is main()" << endl;
srand(time(NULL));
cout << getRand(0, 10) << endl;
return 0;
}