Can someone tell me how to create a random number generator that chooses 2 leap years between 1900 and 2000? I do not know where to even begin. Any help is appreciated. Thanks.
:confused:
Can someone tell me how to create a random number generator that chooses 2 leap years between 1900 and 2000? I do not know where to even begin. Any help is appreciated. Thanks.
:confused:
Try using srand(), rand() and the % operator. You might want to read the man pages for rand() and srand() at http://www.openbsd.org/cgi-bin/man.c...86&format=html first. To get a leap year, the rules are:
1. Year should be divisible by 4
2. Centuries are excluded from rule 1, unless the century is divisible by 400.
From rules 1 and 2, we see that the 1904 is a leap year (obeys rules 1 and 2), 1900 is not (obeys 1 but not 2), 1976 is a leap year (obeys rules 1 and 2), 2000 is a leap year (obeys rules 1 and 2) etc. So now we can formulate an algorithm for generating leap years.
1. Pick a number randomly between 1 and 25.
2. Multiply this number by 4.
3. Add 1900 to it.
Now, if you read the documentation for the rand() function, you'll notice that it returns a # between 0 and RAND_MAX (which is a large number > 25). So, to get a number between 0 and 24, all you have to do is modulo divide by 25. Add 1 to this and you end up with a number between 1 and 25. So if you do this:
randnum = rand() % 25 + 1;
this will ensure that randnum is between 1 and 25.
With that said, your code could look something like this.
Hope this helps :)Code:#include <time.h> #include <stdlib.h> #include <stdio.h> int main(void) { int randnum; /* Seed random # generator with current time. This may be a poor choice for crypto stuff, but may do fine for the problem at hand. Pick some other seed value if you like */ srand(time(NULL)); randnum = (rand() % 25 + 1) * 4 + 1900; /* Get random year */ printf("The year is %d\n", randnum); return 0; }
Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
"Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne
"I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
Thank you for your help.
So anyway, did you get a good grade for your homework?
Not to be rude or anything. But I did not ask for anyone to do my homework. I only asked for help on something I was stuck on. I always believe that you can only learn by doing.