+ 3
Use the modulo (%) operator to generate random numbers within a specific range.
The example below generates whole numbers within a range of 1 to 6. int main () { for (int x = 1; x <= 10; x++) { cout << 1 + (rand() % 6) << endl; } } /* Output: 6 6 5 5 6 5 1 1 5 3 */ but when i wish to use range between 2 to 9 . the output becomes include 10. how its possible?? explain???
4 ответов
+ 4
Try this code
you should use this formula
from + (rand() % (to - from + 1))
https://code.sololearn.com/cQ2273i41tPS/?ref=app
+ 2
rand % (max - min + 1) + min
This is the formula for random number generator in a specific range that I know and it really works.
Replace max with maximum range value and min with minimum range value
0
if (random number) % 9 's result is 8, output be 10 if u want specific range. minimum number is the number you are adding ( 3 + rand() % 9) <- in this example min. num. is 3. and the maximum number is (9 - 1) + 3 equals 11.
Edit:
If you ask why we are doing 9 - 1, because when you divide a number that can exactly be divided by 9 its reminder become 0. (simple math knowledge)
0
the code which you are using here is cout<<1+(rand()%6)<<endl
here what is happeng is that you get a number using rand function then you make reduce it to range 0 to 5 (modulo 6 contains 0,1,2,3,4,5) , then what ever the number is ,you are adding 1 to it.
similar is the case for 2-9 range, lets say rand function gave a number ' x ' and you module 9 converts it to 8 and you added 2 to it, this becomes 10