Results 1 to 5 of 5

Thread: C++ Help

  1. #1
    Banned
    Join Date
    Mar 2002
    Posts
    594

    C++ Help

    I need a little help, can someone teach me how to generate
    a random number and store it as a variable in C++. Thanks.

    Jaguar291

  2. #2
    The random number generator in the STD lib is a little tricky. Just put this function is the code somewhere :

    typedef unsigned int UINT;

    UINT Random(UINT n, UINT seed) {

    srand(seed);
    UINT num = rand();
    UINT ret = (n * num) / RAND_MAX;
    return ret;

    }

    ----That should do it,

    Parameter "UINT n" :
    lets say you want a random number between 1 and 10 ; well then "n" would equal 10.
    Parameter "UINT seed" :
    just set this to any number really, it just get the generator going.

    SANDMAN

  3. #3
    Senior Member
    Join Date
    Jul 2001
    Posts
    420
    Originally posted here by Lucas420

    Parameter "UINT n" :
    lets say you want a random number between 1 and 10 ; well then "n" would equal 10.
    Parameter "UINT seed" :
    just set this to any number really, it just get the generator going.

    SANDMAN
    If I recall the seed parameter is optional but if you don't use it the random number is always the same. That will happen if you do seed it unless you use a changing value such as the time the program is being run. See http://www.cs.cf.ac.uk/Dave/C/node21...00000000000000 for details on the time function.

    Cheers,

    -D

  4. #4
    Senior Member
    Join Date
    Sep 2001
    Posts
    1,027
    The code is ok, but just two little precisions:
    1- You don't have to define the typ UINT... declaring the variables as unsinged int directly works just fine (in fact I believe rand() returns an signed int (although it returns values between 0 and RAND_MAX)

    2- Also, for the seed, most of the time, the time is used:

    // Needs time.h
    #include <time.h>
    //...
    srand( (unsigned)time( NULL ) );


    Ammo
    Credit travels up, blame travels down -- The Boss

  5. #5
    For a simple and somewhat comprehensive information on random numbers, read my tutorial on random nos which i posted here a couple of weeks back. it was titled. " Random Numbers Randomized".
    If u need any further clarification, feel free to post

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •