C++/Random function in Turbo Borland
Expert: Zlatko - 1/29/2011
QuestionHow can I write a random function in a Turbo C++ that will help me in making a gambling game?
AnswerHello Tumi.
Although I do not use turbo C, I believe it uses the standard C library rand function. Here is a sample program to generate random numbers in a desired range.
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
/*
Function getRandom takes a low and high value
and returns a random number r where
low <= r <= high
*/
int getRandom(int low, int high)
{
return rand() % (high - low + 1) + low;
}
int main(void)
{
int i;
/* typically we seed the random number generator with
a random seed value, like the current time.
If you don't seed the random number generator, each run of the
program will make the same random numbers
*/
srand((unsigned int)time(NULL));
for(i = 0; i < 10; ++i)
{
int r = getRandom(-6, 6);
printf("%3d\n", r);
}
}