随机函数:srand()和 rand()配合使用可以生成伪随机数序列,比如生成[1,100]以内的随机数。
rand() 函数在产生随机数前,需要系统提供的生成伪随机数序列的种子,rand()根据这个种子的值产生一系列随机数。
如果系统提供的种子没有变化,每次调用 rand()函数生成的伪随机数序列都是一样的。
一般以系统时间作为种子使用,通常用法如下:
#include <stdlib.h>
#include <time.h>
...
srand(time(NULL));
rand(); //产生100以内随机数:rand()%100;
...
使用随机数函数,如果需要生成的随机数范围较小(比如10以内的随机数),很容易重复。
在某些情形下需要考虑去重问题:
例如:生成 10 个不重复的随机数并存储在数组中。
代码实现如下:
/*
要求:生成10个不重复的数,并放到数组中
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int num=0;
int i = 0;
int count = 0;
int randArr[10];
srand(time(NULL));
while (1)
{
num = rand() % 10;
randArr[count++] = num;
for (int i = 0; i < count - 1; i++)
{
//检查是否重复,重复则剔除
if (randArr[i] == randArr[count - 1])
{
count--;
break;
}
}
if (count == 10)
{
break;
}
}
for (i = 0; i < 10; i++)
{
printf("%d ", randArr[i]);
}
return 0;
}
随机一次运行结果如下:
总结:该示例主要展示了如何使用随机函数,以及特定情形下随机数如何去重的问题。