Click to See Complete Forum and Search --> : Find my mistake with the random command
April 25th, 1999, 02:19 AM
I'm writing a little routine that simulates the rolling of dice,
but it gives the same numbers in the same order every time
I run it, even if I recompile the code each time.
My random routine looks like
randomize();
roll=random(sides)+1;
I'm using Turbo C 4.5. Can you see any problem with the above?
I have stdlib.h and time.h included...
Thanks,
Jason F.
jfahy@sprint.ca
Rick Blommers
April 26th, 1999, 08:23 AM
Hi Jason,
I don't see what you are doing wrong but you could try this:
----
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
srand( (unsigned)time( NULL ) ); // is the same as randomize()
roll = rand()%sides + 1 // is the same as random()
---
randomize() and random() are not standard C !!
maybe in Borland, but not in Microsoft C,
so I advice you to use rand() and srand() like used above
Good Luck,
Rick Blommers
rbl@agp.nl
April 26th, 1999, 11:38 AM
Try this (it will make your output look like dice too!):
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
const int SIZE = 6;
int main()
{
int one, two, total;
srand(time(NULL));
char *DieA[SIZE] = {".", ":", ":.", "::", ":.:", ":::"};
char *DieB[SIZE] = {".", ":", ":.", "::", ":.:", ":::"};
one = rand()%6 + 1;
two = rand()%6 + 1;
total = one + two;
cout << "Die A is " << DieA[one-1] << endl;
cout << "Die B is " << DieB[two-1] << endl;
cout << "Total rolled was: " << total << "\n\n";
return 0;
}
Chris Wheeler
April 27th, 1999, 09:18 AM
I'm not exactly sure how "randomize" works in Turbo C, but the usual problem with random numbers is the seed of the random number generator. Randomizing functions are really just an equation that operates on a number. If you start with the same number every time, your "random" numbers will become predictable for as many as you can remember. Try seeding the random number with an internal time function such as seconds since 1980 or something.
Chris R. Wheeler, MCP
Pensacola Christian College
Desktop Programmer
cwheeler@pcci.edu
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.