Desparate

Discussion in 'Computer Science & Culture' started by Nebula, Jun 1, 2004.

Thread Status:
Not open for further replies.
  1. Nebula Occasionally Frequent Registered Senior Member

    Messages:
    906
    Hi all. I've got another dumb C++ question. I've googled it but didn't really find much useful info.

    All I'm trying to do is use the rand() function to generate a random integer between 0 and 25.

    How can I do this?

    Please Register or Log in to view the hidden image!

    Please Register or Log in to view the hidden image!

     
  2. Google AdSense Guest Advertisement



    to hide all adverts.
  3. Nebula Occasionally Frequent Registered Senior Member

    Messages:
    906
    Alright. I searched a bit more, and after reading this, I solved my original problem with the following code:


    Code:
    int low=1, high=26;
    
    GetChar = (rand() % (high - low + 1) + low);
    Note: I realize in the original post I needed a value between 0-25. I just changed it a bit.


    My question is, WHY IS THIS WORKING?! I don't understand what I'm doing with it. Could someone help me go through how the compiler is looking at this statement?

    Thanks!
     
  4. Google AdSense Guest Advertisement



    to hide all adverts.
  5. okinrus Registered Senior Member

    Messages:
    2,669
    rand() returns an integer between 0 and RAND_MAX. The rand() % (high - low + 1) returns an integer between 0 and high - low because it is finding the remainder by dividing by (high - low + 1). Then low is added to this number so the final return will be between low and high.

    There are better ways of generating random numbers using the rand() function but this is probably the easiest.
     
  6. Google AdSense Guest Advertisement



    to hide all adverts.
  7. Nebula Occasionally Frequent Registered Senior Member

    Messages:
    906
    what is RAND_MAX?
     
  8. testify Look, a puppy! Registered Senior Member

    Messages:
    508
    Modulo (%) is the remainder of division (26%26 returns 0) as you should know by now. The way you did it should actually returns any number between (and including) 1 and 26.

    (rand() % (high - low + 1) + low);
    (rand() % (26 - 1 + 1) + 1);
    rand() % 26 + 1;
    rand() % 26 == any between 0 and 25
    adding 1 to it would mean any between 1 and 26

    oh...and RAND_MAX is the max int that is returned by rand() as set by stdlib
     
  9. Nebula Occasionally Frequent Registered Senior Member

    Messages:
    906
    ah, I think I get it...the value of the expression can't exceed the remainder, right?

    ** slaps forehead **

    Don't know why I didn' see this earlier.
     
Thread Status:
Not open for further replies.

Share This Page