rand() help?

This is a discussion on rand() help? within the C++ Programming forums, part of the General Programming Boards category; I'm trying to generate random numbers between -10 and +10. Any help...below is what I've tried: Code: srand(time(NULL)); for (int ...

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    17

    rand() help?

    I'm trying to generate random numbers between -10 and +10. Any help...below is what I've tried:

    Code:
    srand(time(NULL));
    for (int i=0;i<10;i++)
    	cout << ((rand() % -10) + -10 + 10) << endl;

  2. #2
    Registered User
    Join Date
    Feb 2009
    Posts
    138
    it's easier to start with a positive range and then move it into the negatives. get a random number from 0 to 20 and then subtract 10.
    Code:
    rand() % 20 - 10

  3. #3
    "I Win!" by U. Lose vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,552
    actually x%20 has values from 0 to 19 and rand()%20 -10 will give [-10;9] range
    To be or not to be == true

  4. #4
    Registered User
    Join Date
    Feb 2009
    Posts
    17
    Thanks!

  5. #5
    Registered User
    Join Date
    Feb 2009
    Posts
    138
    that's right. there are 4 ways "between x and y" could be interpreted.

    [x,y] - all inclusive
    [x,y) - right exclusive
    (x,y] - left exclusive
    (x,y) - all exclusive

    usually [x,y) is what's wanted, and that's what my suggestion does. but if you want one of the others, it's easy to change to suit any of the interpretations with simple math.
    Last edited by Meldreth; 02-18-2009 at 02:34 PM.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21