This is the mail archive of the
mailing list for the Cygwin project.
Re: Random Number Generator
- To: HRahman10 at aol dot com
- Subject: Re: Random Number Generator
- From: Jonathon Merz <jmerz42 at earthlink dot net>
- Date: Mon, 30 Apr 2001 13:17:54 -0500
- CC: cygwin at cygwin dot com
- References: <firstname.lastname@example.org>
- Reply-To: jmerz42 at earthlink dot net
A number of problems here...
The reason only zeroes are being output is due to everything being
interpreted as an integer and truncating to 0 when it is less than 1. The
best bet make the 10 that you multiply 10.0 or else cast it as float or
double.If you desire integer results, you can then cast input1 as int when you
need it as such.
Another potential problem is (RAND_MAX +1). This overflows (gcc gives a
warning on compile), essentially giving you (RAND_MAX * -1) on any system
where RAND_MAX is equal to MAX_INT, which as far as I know is most systems.
If this is deliberate, for clearer coding, it would be better to write it as
the latter, in addition to the fact, that if the code is ever compiled on a
system where RAND_MAX is different than MAX_INT, it will not wrap, or else it
may wrap differently.
In short, the following line:
input1 = rand() * 10 / (RAND_MAX + 1);
input1 = rand() * (float)10 / (RAND_MAX);
input1 = rand() * (float)10 / (RAND_MAX * -1);
if the negation of RAND_MAX was deliberate.
Hope this helps.
> Hi!, I'm writing a program using the random number genrator rand() defined in <stdlib.h>. I've written the following program to test it:
> void main()
> int input1, i;
> for (i=0; i<20 ; i++)
> input1 = rand() * 10 / (RAND_MAX + 1);
> printf("random numbers %i\n",input1);
> BUT, the results I get are all zeros. Is there something wrong with the gcc compiler provided by cygwin, because I've tested this program at university, and it outputs random numbers correctly.
If you had a million Shakespeares,
could they write like a monkey?
Want to unsubscribe from this list?
Check out: http://cygwin.com/ml/#unsubscribe-simple