+ 2
How can I set a range for random number in c++ ?
I want to set a range for random number . For ex : rand() % (range) Range means like 10 - 30 How can I do that ?
6 Respostas
+ 4
10 + rand() % (31-10)
+ 4
And I like to make this into a function, so I can use whatever ranges I want:
int randAtoB(int a, int b) {
return (rand() % (b - a + 1)) + a;
}
//Now I can call it in main
int num = randAtoB(22, 101);
+ 3
rand() % (31-10) = rand() % 21
It generates numbers from 0 to 20, by adding 10
10 + rand() % 21
it will generate number from 10 to 30
http://www.cplusplus.com/reference/cstdlib/rand/
+ 2
It worked ...but can you please explain it to me ?😃😃
+ 2
Ohh...thanks..I understood 😃😃
- 2
Hi I am new