[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]

Why am I not getting the results I expect...


I have a piece of code where I generate a random number between 1 and n.  I
also want to make sure that each random number is generated only once.

Here is a snippet of code:

int num_of_arts;
int display_article_number;
int * article_displayed;	/* Flags stored here */

num_of_arts = 24;

/* Make enough space to store the flags */
article_displayed = (int *) calloc(num_of_arts, sizeof(int));

display_article_number = 1 + (int) (((float) num_of_arts) * random() /

while (*(article_displayed+display_article_number-1) == 1) {
    display_article_number = 1 + (int) (((float) num_of_arts) * random() /

I expect this piece of code to generate a random number between 1 and 24. 
But it also generates number > 24.  What am I doing wrong?  I got the algo
to generate a random number between 1 and n from the manpage for rand()
(not random()).

Marge: Okay, but you've accomplished a lot!  You've made me very happy.
Homer: Oh, yeah, they'll put me on a stamp for that!
Sudhakar C13n    http://www.aunet.org/thaths/    Lead Indentured Slave