You are here:

C++/Random function in Turbo Borland

Advertisement


Question
How can I write a random function in a Turbo C++ that will help me in making a gambling game?

Answer
Hello 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);
   }
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2016 About.com. All rights reserved.