delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/10/07/09:11:07

Date: Tue, 7 Oct 1997 15:06:57 +0200 (MET DST)
From: Wojciech Piechowski <voyt AT delta DOT ds2 DOT pg DOT gda DOT pl>
To: Robert Debeljakovic <rdebelj AT wt DOT com DOT au>
cc: djgpp AT delorie DOT com
Subject: Re: [Q] Whats wrong here...
In-Reply-To: <61canb$kjf$1@kurica.wt.com.au>
Message-ID: <Pine.GSO.3.96.971007145640.23983D-100000@delta.ds2.pg.gda.pl>
MIME-Version: 1.0


On Tue, 7 Oct 1997, Robert Debeljakovic wrote:

> Ok, look at the following code....
> ----------------------------------------------------
> #include <stdio.h>
> #include <stdlib.h>
> #include <conio.h>
> 
> void Random(int MaxValue)
> {
> int x;
> 
> x= -1;
> if((x < 0)||(x > MaxValue))
  ^^
  ^^  I recommend
      while((x < 0)...

>   x=rand();
> printf("[%d]\n",x);
> }
> 

However, the algorithm you use is not effective: rand() returns an
unsigned integer in a range 0..0x7fffffffL (it's over 2*10^9). It may take
a while until it returns a number <100.

For small MaxValue (10,100.. 1 000 000) you can write

void Random(int MaxValue)
{
   int x;
   x=rand() % MaxValue;
   printf("[%d]\n",x);
}

The larger MaxValue, the less uniform distribution you get.


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019