Thread: random numbers in MSCV++ 6.0?

  1. #1
    Registered User samGwilliam's Avatar
    Join Date
    Feb 2002
    Location
    Newport
    Posts
    382

    random numbers in MSCV++ 6.0?

    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?

  2. #2
    Fingerstyle Guitarist taylorguitarman's Avatar
    Join Date
    Aug 2001
    Posts
    564
    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

  3. #3
    Registered User samGwilliam's Avatar
    Join Date
    Feb 2002
    Location
    Newport
    Posts
    382
    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;

  4. #4
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,823
    Close - that'll give you a random number up to 4, not 5

  5. #5
    Registered User samGwilliam's Avatar
    Join Date
    Feb 2002
    Location
    Newport
    Posts
    382
    Ah, yes. You are right. Cheers!

  6. #6
    Registered User
    Join Date
    Feb 2002
    Posts
    1
    #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 08:06 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Doubts regarding random numbers generation
    By girish1026 in forum C Programming
    Replies: 9
    Last Post: 12-31-2008, 10:47 PM
  2. random numbers
    By mesmer in forum C Programming
    Replies: 4
    Last Post: 10-24-2008, 01:22 PM
  3. random numbers limit
    By HAssan in forum C Programming
    Replies: 9
    Last Post: 12-06-2005, 07:51 PM
  4. Generating 100k to 1 million unique random numbers
    By Ariod in forum C Programming
    Replies: 4
    Last Post: 08-26-2005, 12:59 PM
  5. Help generating random numbers in MFC
    By drb2k2 in forum C++ Programming
    Replies: 3
    Last Post: 04-08-2003, 08:52 AM