C语言:如何产生不重复的随机数字?

2025年02月23日 05:54
有5个网友回答
网友(1):

数学意义上的随机数在计算机上已被证明不可能实现。通常的随机数是使用随机数发生器在一个有限大的线性空间里取一个数。“随机”甚至不能保证数字的出现是无规律的。

我觉得你的程序逻辑似乎不对,看程序a的值应该来自数组num[],假如在第一个for循环中生成的x值为1,第二次仍然生成1,程序将陷入死循环,又或者a是某个特定值,只是你应该给出说明。

使用系统时间作为随机数发生器是常见的选择,参考下面的随机输出1个1~99数字的程序:

#include
#include
#include
int main(void)
{
int i;
time_t t;
srand((unsigned) time(&t));
printf("Ten random numbers from 0 to 99\n\n");
for(i=0; i<10; i++)
printf("%d\n", rand() % 100);
return 0;
}

网友(2):

----------------VC6测试通过----能产生不相同的数--------------------
#include
#include
#include

void main()
{
int x;
int num[10];//声明数组。
srand(unsigned(time(NULL)));
for(int i=0;i<6;i++)
{//取6个不重复的整数放到数组num中。
leap:x=rand()%10; //此处我将其改为0-9范围了。你可以改大。
for(int j=0;j {
if(num[j]==x)// 此数组没声明。
{
//i=0; //此处不能改写i的值。如果你改了,就不会循环与数组中的数比较了。当然就可能出现重复的情况了。
goto leap;
}//if

}//for
num[i]=x;// 如果不等就插进数组num相应位置中。
printf("%d ",num[i]); //此处打印时,要空一格,否则数据都连在一起了。
}//for
printf("\n");
}//main

网友(3):

rand(产生随机数)
相关函数 srand,random,srandom

表头文件 #include

定义函数 int rand(void)

函数说明 rand()会返回一随机数值,范围在0至RAND_MAX 间。在调用此函数产生随机数前,必须先利用srand()设好随机数种子,如果未设随机数种子,rand()在调用时会自动设随机数种子为1。关于随机数种子请参考srand()。

返回值 返回0至RAND_MAX之间的随机数值,RAND_MAX定义在stdlib.h,其值为2147483647。

范例 /* 产生介于1 到10 间的随机数值,此范例未设随机数种子,完整的随机数产生请参考
srand()*/
#include
main()
{
int i,j;
for(i=0;i<10;i++)
{
j=1+(int)(10.0*rand()/(RAND_MAX+1.0));
printf("%d ",j);
}
}

执行 9 4 8 8 10 2 4 8 3 6
9 4 8 8 10 2 4 8 3 6

srand(设置随机数种子)
相关函数 rand,random srandom

表头文件 #include

定义函数 void srand (unsigned int seed);

函数说明 srand()用来设置rand()产生随机数时的随机数种子。参数seed必须是个整数,通常可以利用geypid()或time(0)的返回值来当做seed。如果每次seed都设相同值,rand()所产生的随机数值每次就会一样。

返回值

范例 /* 产生介于1 到10 间的随机数值,此范例与执行结果可与rand()参照*/
#include
#include
main()
{
int i,j;
srand((int)time(0));
for(i=0;i<10;i++)
{
j=1+(int)(10.0*rand()/(RAND_MAX+1.0));
printf("%d ",j);
}
}

执行 5 8 8 8 10 2 10 8 9 9
2 9 7 4 10 3 2 10 8 7

网友(4):

运行绝对正确,结果如下:
1: 4 9 7 5 6 1 9 3 1
2: 2 7 3 9 5 8 1 6 4
代码如下:(若是C,改头文件为stdio.h和time.h,并把cout改为printf即可)
-------------------------------------
//random.cpp
//author: kt
#include
#include
using namespace std;

void S_Rand()
{
time_t t=time(0);
srand( (unsigned)t );
}

int CreatRand( int a, int b)
{
return a+rand()%( b-a );
}

bool NeverAppear( int vec[], int ele, int n)
{
for ( int i=0; i if (ele==vec[i])
return false;
}

return true;
}

void PrintResult( int vec[], int n)
{
for ( int i=0; i {
cout< }
cout<}

int main()
{

const int n=9;
const int a=1,b=10;

int* randnum=new int[n];
S_Rand();

for ( int i=0; i int temp=0;
do {
temp=CreatRand(a,b);
}while ( !NeverAppear( randnum, temp,i) );

randnum[i]=temp;
}

PrintResult( randnum, n );

return 0;
}

网友(5):

e[q]=rand()
%
1+20;
你这里的意思我不太明白
取模1?那一定是0啊
再+20
那就是说不管是什么数最后e[q]只能是20.。。。还有这里srand=(time(NULL)+q);你确定那里有个等号吗???