Being new to Visual C++ (I'm a Borland Boy) I tried to generate random numbers with the random (int) function, normally found in the stdlib.h file but the compiler doesn't recognise it. Where is it under MS?
This is a discussion on random numbers in MSCV++ 6.0? within the C++ Programming forums, part of the General Programming Boards category; Being new to Visual C++ (I'm a Borland Boy) I tried to generate random numbers with the random (int) function, ...
Being new to Visual C++ (I'm a Borland Boy) I tried to generate random numbers with the random (int) function, normally found in the stdlib.h file but the compiler doesn't recognise it. Where is it under MS?
try this:
you need the stdlib and time headers
Code:srand(time(NULL)); // seeds the random number generator (only called once) int RandomNumber = rand(); // generate a random number
But rand accepts no parameters, so I'll have to write my own clamping code, yes?
Like:
// Random number between 0 and 5:
num = rand () % 5;
Close - that'll give you a random number up to 4, not 5
-Govtcheez
govtcheez03@hotmail.com
Ah, yes. You are right. Cheers!
#include <iostream>
#include <ctime>
using namespace std;
int randInt( int low, int high );
int main()
{
srand(unsigned(time(NULL)));
cout << "Random Number: " << randInt( 1, 10 ) << endl;
return 0;
}
int randInt( int low, int high )
{
return low + rand() % ( high - low + 1 );
}
* This is untested, sorry if it doesnt work.
Last edited by tijiez; 02-07-2002 at 07:06 PM.