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

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

If we can safely assume that you're compiling this on a Linux machie,
(you'd probably not have posted to this list otherwise, would you?)
then the random () library function returns an integer (long int, 
actually; unless my manpages are dated; or yours). In which case you 
don't need to do any int-to-float-and-then-back-to-int conversions 
which are fraught with rounding related dangers which probably are 
giving you your headache.

So if you have random () returning long on your machine, this should
    ((int) (random ()) % 24) + 1

The number will, of course, also serve as the index into the array.

Glad to be of assistance.


> 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() /
> (RAND_MAX+1.0));


Venkatesha Murthy G.