RAND() [英] rand()

查看:86
本文介绍了RAND()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好;

i有这样的功能,

它总是有相同的数字并且如果我拿走了这个号码就会出错

for循环中的函数

void list :: getWords()

{int num;


for(int m = 0; m <20; m ++)

{

srand((无符号)时间(NULL));

num =(rand() %41)-1;

节点* ptr;

ptr =新节点;

ptr-> word = wordsall [num];

append(ptr); //附加到链表

}

}

hi all;
i have a function like this,
it always rands the same number and gives error if i take the srand
function out of the for loop
void list::getWords()
{ int num;

for(int m=0;m<20;m++)
{
srand((unsigned)time( NULL ));
num=(rand()%41)-1;
node *ptr;
ptr=new node;
ptr->word=wordsall[num];
append(ptr);//appends to the linked list
}
}

推荐答案

为什么在每次迭代时重新设置随机数生成器?这是'

几乎可以保证给你一个非随机发行版。


--smw

Why reseed the random number generator on each iteration? That''s
pretty much guaranteed to give you a nonrandom distribution.

--smw


jw写道:
大家好;
我有一个这样的函数,
它总是使用相同的数字并且如果我拿走srand会出错来自for循环的函数
void list :: getWords()
{int num;

for(int m = 0; m< 20; m ++)
{
srand((unsigned)time(NULL));
num =(rand()%41)-1;
node * ptr;
ptr = new节点;
ptr-> word = wordsall [num];
append(ptr); //附加到链表
}
}
hi all;
i have a function like this,
it always rands the same number and gives error if i take the srand
function out of the for loop
void list::getWords()
{ int num;

for(int m=0;m<20;m++)
{
srand((unsigned)time( NULL ));
num=(rand()%41)-1;
node *ptr;
ptr=new node;
ptr->word=wordsall[num];
append(ptr);//appends to the linked list
}
}




你只需要调用一次srand,所以将它移出for循环就可以了。

更适合它。你得到的编译器错误是什么?


另外,下次请发布完整的,最小的,*可编译的*代码每

FAQ 5.8 。


Kristo



You only need to call srand once, so moving it out of the for-loop is a
better place for it. What''s the compiler error you''re getting?

Also, next time please post complete, minimal, *compilable* code per
FAQ 5.8.

Kristo


如果我把它带出循环它会在跑步时崩溃,但是现在它没有

崩溃,但总是有相同的数字

if i take it out of the loop it crashes while running,but now it doesnt
crash but always rands the same number


这篇关于RAND()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆