用rand()的函数,生成随机数,头文件<cstdlib>
该函数需要一个起始种子,若没有指定该种子,则每次运行时会产生相同的数字流
#include <stdio.h>
#include <cstdlib>
#include <ctime>
int main()
{
printf("time:%ld\n", time(0));
for (int i = 0; i < 10; i++)
{
int num = rand();
printf("num:%d\n", num);
}
system("pause");
return 0;
}
用time的函数获取种子,time(0)函数返回当前格林尼治标准时间与格林尼治标准时间1970年0分0秒的时间间隔。头文件<ctime>。
time(0) 和 time(NULL)的功能相同。
#include <stdio.h>
#include <cstdlib>
#include <ctime>
int main()
{
unsigned seed;
seed = time(0);
srand(seed); //为随机数生成器提供一个种子
for (int i = 0; i < 10; i++)
{
int num = rand();
printf("num:%d\n", num);
}
//生成[1,max_n]之间的随机数
int max_n = 13;
int out_n = rand() % max_n + 1;
printf("[1,max_n] out_n:%d\n", out_n);
//生成[min_n,max_n]之间的随机数
int min_n = 5;
out_n = rand() % (max_n - min_n + 1) + min_n;
printf("[min_n,max_n] out_n:%d\n", out_n);
system("pause");
return 0;
}
生成指定长度的随机字符串
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <string>
std::string rand_str(int len)
{
std::string str = "";
for (int i = 0; i < len; ++i)
{
switch ((rand() % 3))
{
case 1:
str += ('A' + rand() % 26);
break;
case 2:
str += ('a' + rand() % 26);
break;
default:
str += ('0' + rand() % 10);
break;
}
}
return str;
}
int main()
{
srand((unsigned)time(0));
for (int i = 0; i < 10; i++)
{
std::string str = rand_str(13);
printf("%s\n", str.c_str());
}
system("pause");
return 0;
}