+ 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 ?

29th Jun 2019, 10:23 AM
Foxie
Foxie - avatar
6 Antworten
+ 4
10 + rand() % (31-10)
29th Jun 2019, 10:29 AM
Mina Yossry
Mina Yossry - avatar
+ 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);
29th Jun 2019, 3:06 PM
Zeke Williams
Zeke Williams - avatar
+ 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/
29th Jun 2019, 10:34 AM
Mina Yossry
Mina Yossry - avatar
+ 2
It worked ...but can you please explain it to me ?😃😃
29th Jun 2019, 10:30 AM
Foxie
Foxie - avatar
+ 2
Ohh...thanks..I understood 😃😃
29th Jun 2019, 10:35 AM
Foxie
Foxie - avatar
- 2
Hi I am new
9th Jul 2019, 7:53 PM
Taoana Poelano