How exactly do I write this code.
}
int i;
srand(time(NULL));
i = rand();
}
That is the bases without the 1-7 right? How do I get it to so that the variable i is between 1-7. I'm trying to make a dice program if that helps, I got all of it but this.
Language C: rand() and srand() with time - Getting a value between 1 and 7, also re-seeding the generator?
Try either
i = (rand() % 7)
or
i = (rand() % 6) + 1;
Reply:See my comment below. That will get you a number, but on most unixes it will not provide you a random distribution - the lower bits are not distributed well. Report It
Reply:rand() returns a random int between 0 and RAND_MAX, so the simplest way is just to do rand()%(RAND_MAX/NUM) to get a random number between 0 and NUM.
However, this is not the best way. On many C installations the rand() function is not so good, especially the lower digits. From the comment of the man rand command on my linux system:
"In Numerical Recipes in C: The Art of Scientific Computing
(William H. Press, Brian P. Flannery, Saul A. Teukolsky,
William T. Vetterling; New York: Cambridge University
Press, 1990 (1st ed, p. 207)), the following comments are
made:
"If you want to generate a random integer between 1
and 10, you should always do it by
j=1+(int) (10.0*rand()/(RAND_MAX+1.0));
and never by anything resembling
j=1+((int) (1000000.0*rand()) % 10);
(which uses lower-order bits)."
"
Reply:try converting the value that the function returns to you generally it is something like .8736 then you can close it to 8 but then 8 isn't useful so use a condition to get rid of 7,8,9,0 i did a dice function that way
survey monkey
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment