本文介绍了循环中重复的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于每个不同的循环,需要在0和1之间建立一个随机数。
为(1到10000)
调用RandomKey函数,以便生成不同的随机数。
但是问题是每次迭代都得到相同的数字。
RandomKey函数如下:
void RandomKey b $ b {
srand((unsigned)time(0));
for(int k = 0; k {
Act_num [k] .Priority =(rand()%10000)* 0.0001; // random数字
}
for(int i = 0; i arr [i] = Act_num [i] ;
我如何解决这个问题?
至少有三件事你应该验证:
- 在您的计划中只拨打
srand
一次
- 如果
srand
被多次调用,或者您的程序每秒运行多次,则。 - 如果每个随机数只应为0或1,你应该调用
(int)(rand()& 1)
得到从零到一个均匀分布的数字。如果您需要在0.0和1.0之间的浮动,则需要以不同的方式。
:如果您只想要一个在零和一之间的随机浮点数,请参阅
A need to generatera random numbers between 0 and 1 for every different loop.
for ( 1 to 10000)
a call RandomKey function so as to generate different random numbers.But the problem is every iteration i get same numbers.
RandomKey function is as follows:
void RandomKey ()
{
srand((unsigned)time(0));
for (int k=0;k<ActivityNumber;k++)
{
Act_num[k].Priority=(rand()%10000)*0.0001;//random number
}
for (int i=0;i<ActivityNumber;i++)
arr[i]=Act_num[i].Priority;
How can i solve the problem?
解决方案
(I'm restating the other suggestions here.)
There are at least three things you should verify:
- Only call
srand
once in your program - If
srand
is called more than once, or your program is run many times per second, then do not use time(0) to initialize srand. - If each random number should only be 0 or 1, you should call
(int)(rand() & 1)
to get uniformly distributed numbers from zero to one. If you need floats between 0.0 and 1.0, you need to do it differently.
EDIT: If you just want a random floating point number between zero and one, see Generating random number between [-1, 1] in C?
这篇关于循环中重复的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
08-23 16:26