CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: Random Number Generation

  1. #1
    Join Date
    Mar 2000
    Posts
    20

    Random Number Generation

    Is there a function in MFC to generate a random number that is LESS
    THAN a user-defined upper limit?

    When I used to program in Turbo C I had used such a function. But in
    MFC, I see that there are only functions that generate random numbers
    between a LOWER limit and the constant RAND_MAX (which I can't change
    anyway). I cannot set the upper limit.

    I am looking for a method other than comparing each generated random
    number with the upper limit & discarding bigger numbers.
    Thanx a lot.


  2. #2
    Join Date
    Nov 1999
    Location
    Dresden / Germoney
    Posts
    1,402

    Re: Random Number Generation

    Hi,

    rand() % 6
    will generate random number 0..5

    Note that rand() is not useful for statistical purposes - and the modulo makes it worse (a bit). But if it just should 'look random', or it is for a game or something, it#s fine.

    Peter


  3. #3
    Join Date
    Oct 2000
    Posts
    3

    Re: Random Number Generation

    // No such luck.
    // Try this trick.

    LONG SomeClass::Random(LONG nMin, LONG nMax)
    {
    // use modulus to return range then add nMin to move to offset.
    return rand() % (nMax-nMin+1) + nMin;
    }


  4. #4
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,716

    Re: Random Number Generation



    srand((unsigned)time(NULL));

    // Generate random number within the range : 0 to iMax

    int iMax = 250;

    int newRan = rand() % (unsigned)(iMax+1);







  5. #5
    Join Date
    Mar 2000
    Posts
    20

    Thanks guys

    Thanks a lot for the help guys.
    Really appreciate it.


Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)