1

Whenever I try to run this code it returns numbers between 10 and 19 too but I intend return in the range between 20 and 30. I thought the pattern would be: %min+range but it seems useless although %50+50 turns back numbers between 50 and 99 but any other minimum does not work. Why?

#include<iostream>
#include<cstdlib>
#include<ctime>

using namespace std;
int main()
{
    srand(time(0));
    for(int i=1; i<100; i++)
    {
        cout<<rand()%20+10<<endl;
    }
    return 0;
}
user1030
  • 23
  • 2
  • Try `rand()%10+20` – harper Jul 02 '16 at 07:15
  • This doesn't answer your question, but see [this](https://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator) if you're worried about your random number distribution. – mkal Jul 02 '16 at 07:37

3 Answers3

3

This is because you have it backward. It is %range + min. The modulus function returns the remainder of the division.
So say you were to carry out a random number mod 20. The result would be in the range from 0 to 19. If I were too add a number 'num' to the modulus, I would get a range of
0 + num to 19 + num

Vaibhav Bajaj
  • 1,934
  • 16
  • 29
2

The modulus operator % gets the remainder when divided by a number. In this case, rand()%20 returns a value from 0 to 19. Adding 10 to this gives a value between 10 and 29 inclusive.

If you want a value between 20 and 30, doing rand()%10 will give you a number from 1 to 9, and you can then add 20 to get a number from 20 to 29 inclusive.

In summary: rand() % 10 + 20 returns a number in [20,30).

N. Shead
  • 3,828
  • 1
  • 16
  • 22
1
#include<iostream>
#include<cstdlib>
#include<ctime>

using namespace std;
int main(){
    srand(time(NULL));
    for(int i=0; i<100; i++)
        cout<<rand()%11+20<<endl;
    return 0;
}

The code above is for generating 100 random values between 20 and 30(both inclusive). The pattern you are asking for would be instead: %range+min. As for the case %50+50, returns the correct answer because here range=min=50.