Re: rand and srand
- From: Falcon Kirtaran <falconnews@xxxxxxxxxxxxxxxx>
- Date: Sun, 09 Mar 2008 14:57:38 -0600
Bill Cunningham wrote:
I am stumped on this one. I tried two methods and something just doesn't seem right. I'll try my new syle.
#include <stdio.h>
#include <stdlib.h>
main() {
srand(2000); /*seed unsigned */
printf("%u",rand());
}
Now I get a number much larger than 2000. Also when I also try RAND_MAX with srand from time to time.
With main I was always told int was the default type and didn't need to be declared. Main() has always worked. I hope this code is much more readable.
Bill
The function rand() returns a value between 0 and RAND_MAX, not between 0 and what you pass to srand(). The latter function only sets the seed for the random number generator (on which the next random number will be based).
If you want to have a non-predictable sequence of random numbers, it's often a good idea to set the seed to something that is not a literal and will change each time the program is executed.
Additionally, if you want to generate a random number between 0 and 2000, the code to do that uses the modulus operator, thusly:
printf("%u\n", (rand() % 2001));
For one, without the \n (newline), nothing will separate your numbers from each other. The second part of this is the % 2001. That divides the value from rand() by 2001, and returns the remainder - so the number can be anything from 0 to 2000. If rand() returns 2001, the modulus makes it 0, etc.
As for your main(), I wasn't actually aware that such code was legal C. My guess is that it is actually void main(), because you never return a value from it, so the exit status of your program is most likely undefined. It is a good idea, particularly in UNIX, to declare it int, and return 0 at the end (unless the program failed).
--
--Falcon Kirtaran
.
- Follow-Ups:
- Re: rand and srand
- From: MisterE
- Re: rand and srand
- From: Jack Klein
- Re: rand and srand
- From: Flash Gordon
- Re: rand and srand
- From: Johannes Bauer
- Re: rand and srand
- From: Bill Cunningham
- Re: rand and srand
- References:
- rand and srand
- From: Bill Cunningham
- rand and srand
- Prev by Date: Re: all.h
- Next by Date: Re: rand and srand
- Previous by thread: rand and srand
- Next by thread: Re: rand and srand
- Index(es):
Relevant Pages
|