请高手帮我看看为何我的c语言生成的随机数都相同?我刚开始学。

2025-05-15 15:49:04
推荐回答(5个)
回答1:

原因: time(0)返回的是系统的时间(从1970.1.1午夜算起),单位:秒,而那个循环运行起来耗时连0.000001秒都不到! 也就是说,srand(time(0)) 连着4次的种子是一样的,种子一样,生产的随机数当然是一样了。

srand的例子,你参考下就行:
/* RAND.C: This program seeds the random-number generator
* with the GetTickCount, then displays 10 random integers.
*/

#include
#include
#include

void main( void )
{
int i;
/* Seed the random-number generator with GetTickCount so that
the numbers will be different every time we run.
*/
srand(
GetTickCount()
);
/* Display 10 numbers. */
for(
i = 0; i < 10;i++
)
printf(
"%6d\n", rand()
);
}

回答2:

#include
#include

int newNum(int a, int b, int *num)
{
int n = (int)((double)rand() / ((double)RAND_MAX + 1) * (b - a)) + a + 1;
for(int i = 0; i < b - a; i++)
{
if(n == num[i])
n = newNum(a, b, num);
}
return n;
}

int* rand(int a, int b)
{
int *num;
num = new int[b-a];
for(int i = 0; i < b - a; i++)
{
num[i] = newNum(a, b, num);
}
return num;
}
int main(int argc, char* argv[])
{
srand((unsigned int)time((time_t *)NULL));

int * num = rand(0, 20);
for(int i = 0; i < 20; i++)
printf("%d\n", num[i]);

delete[] num;
return 0;
}

有两年多没来这了,今天睡觉之前给你答一个
要注意几点:
一、这个例子只是最简单的实现,实际项目是不可能用这么简陋的程序,只能供学习用
二、尽管每次运行都srand了一次,但产生的随机数依然是伪随机数,请参考伪随机数定义
三、windows平台上通用的做法是取系统运行时间为种子,但你的题目要求用C,所以我只有用C函数了,其它平台开发没弄过
四、这段程序没有纠错能力,自己写代码一定要注意这些细节,好的习惯决定你的代码质量
五、new之后不要忘了delete
六、计算大量随机数时这段程序可能会不适用,并且效率低下,另外希望你可以用C++重写,用STL可以极大的改进效率
最后你可以找一些成熟的伪随机数生成的例子进行学习,希望你能在编程的过程中找到自己的乐趣
另外,站长团上有产品团购,便宜有保证

回答3:

printf("%d %c %d=\?\n",b,d,c);
这一句 b d c 显示出来随机应该是不会有问题的吧?

printf("score=%d\n",j);
这个就可定不是随机的啦。

回答4:

给你看个很简单明了的例子吧,相信你就懂了。
srand((unsigned)time(NULL));//随机数据种子
for(int a=0; a<20; a++)
{
int n = rand()%25;//产生0到25大小的随机数
printf("%d",n);
}

回答5:

没有问题,就是开头少了个#include