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

Thread: Rand. Numbers

  1. #1
    Guest

    Rand. Numbers

    In vc++ 5, how would I generate a random # bewtween ... 1 - 13 ( or any #).
    I got it where it will give me random #'s but cant find a way to limit it to between 2 #'s.. The docs say to use RAND_MAX but gives no clue as to how to set it... if you know any other ways....help please.
    Thank you!



  2. #2
    Join Date
    Apr 1999
    Location
    San Francisco, CA
    Posts
    32

    Re: Rand. Numbers

    Use the modulus operator (%) to confine the random number to a range. If you want 1-13, I would do the following:

    int RandNumber = (rand() % 13) + 1; // rand() % 13 gives a number between 0 and 12,

    Chris Hafey


  3. #3
    Join Date
    May 1999
    Location
    Oregon, USA
    Posts
    302

    Re: Rand. Numbers

    To expand a little on the previous post :

    int RandomRange( int min, int max )
    {
    // determine range of values
    int range = max - min;

    // idiot check
    if( range <= 0 )
    return 0;

    // get random value
    int value = rand();

    // offset value to range
    return ( value % ( range + 1 ) ) + min;
    }




  4. #4
    Guest

    Re: Rand. Numbers

    going off the example you all have laid out for me then would I still have to "seed" it?? ( currently it is seeded using the time function)
    thank you soo much!


  5. #5
    Join Date
    Apr 1999
    Location
    San Francisco, CA
    Posts
    32

    Re: Rand. Numbers

    If you don't seed the generator, rand() will return the same values each time you run the program. Most programs seed it once, when the program first starts up. Using the time to seed the generator is fine for most applications, as long as you don't care if someone else can reproduce the random numbers. Using this approach in a security application would not be appropriate because it would be too easy to reproduce the random numbers.

    Chris Hafey


  6. #6
    Join Date
    Apr 1999
    Posts
    9

    Re: Rand. Numbers

    Nope,its for a cheesy little game, trying to learn and the tutorials are way to confusing, I was
    learning C++ ( DJGPP ) and moved on to VC++.. anyway I thought I would
    just div in and learn... getting there, but the lack of info.... but
    thank you, now I just need to find info on reading items from files!
    Thank you..


Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured