Re: random milliseconds between 0 and 4 seconds.
Joe, G.I. wrote:
Ian Collins wrote:
Joe, G.I. wrote:
Hi all,
I'm trying to generate about 50 numbers as milliseconds between 0 and 4
seconds and it's driving me crazy.
Can anyone help out on how to do this? Any help much appreciated.
What have you tried so far?
Here's what I'm doing. I'm trying to generate in this example 100 random
values between 0 and 4 seconds. My problem is that my times (generated
random numbers) are all coming out to the same value.
srand(time(0));
for (int i = 0; i < 100; i++) {
ClassA *a = new ClassA();
a->set_start();
a->set_execute();
}
a) You leak memory big time in this code. At each iteration, a new ClassA
object is created. Pointers to these objects are not kept.
b) The method set_start() is not given. I shall assume that it does noting.
bool ClassA::set_execute()
{
exec_time = generate_random();
return true;
}
a) Why is there a return value?
b) Why is this initialization not part of the constructor of ClassA?
int ClassA::generate_random()
{
int r = (rand() / (RAND_MAX + 1.0) * 4000);
a) That will not generate a uniform distribution (unless RAND_MAX has an
unlikely value). However, it might be close enough for you purposes.
b) Why is this not static?
printf("r = %d\n", r);
return r;
}
The following prints different values:
#include <stdio.h>
#include <stdlib.h>
int main ( void ) {
srand( 0 );
for ( int i = 0; i < 100; ++i ) {
int r = ( rand() / (RAND_MAX + 1.0) * 4000 );
printf("r = %d\n", r );
}
}
Since your code sample does not compile, it is hard to spot where it
departs.
Best
Kai-Uwe Bux