delorie.com/archives/browse.cgi | search |
From: | elric AT wheel DOT dcn DOT davis DOT ca DOT us (Jeffrey Taylor) |
Newsgroups: | comp.os.msdos.djgpp |
Subject: | Re: Randomization of Numbers with rand() and stdlib.h |
Date: | 30 Sep 1996 16:00:55 GMT |
Organization: | Davis Community Network - Davis, California, USA |
Lines: | 31 |
Message-ID: | <52oqrn$ml@mark.ucdavis.edu> |
References: | <19960930 DOT 074610 DOT 11630 DOT 0 DOT wilbur3 AT juno DOT com> |
NNTP-Posting-Host: | wheel.dcn.davis.ca.us |
To: | djgpp AT delorie DOT com |
DJ-Gateway: | from newsgroup comp.os.msdos.djgpp |
Will C Stockwell (wilbur3 AT juno DOT com) wrote: : I am trying to randomize numbers between 0 and 15. But when I use the : stdlib.h file and the rand() function. I get the same number every time. : It's something like 25049302. Really long. I have set the RAND_MAX macro : value to 15 with a define statement but I still get the 25049302. Is : their another way to get random numbers? With time as a random factor : maybe? Thanks. : You are using the RAND_MAX macro the wrong way around. It tells you what the maximum value of rand() is. From your problem description, I expect you are calling rand() once per program run. Rand() returns values in a psuedo-random sequence. To start at a different place in the sequence use srand() first. A typical way to do this is : #include <time.h> . . . srand(time(0)); x = rand(); The easy way to get numbers in the range 0 to 15 is (rand() % 16) or the slightly faster (rand() & 0xF). There was an article in Dr. Dobbs on getting truely random numbers. Too much run time for most uses, but useful ideas in the pieces. Jeff T
webmaster | delorie software privacy |
Copyright © 2019 by DJ Delorie | Updated Jul 2019 |