I need a random function for number betwen 11 and 99. I wrote this:
int random (void){
int i2;
i2=11+(rand()%99);
return i2;
}
but the numbers go over 99. Why?
Because if rand() return 98, then 98 % 99 is 98 and 98 + 11 > 99.
To do this, you need
i2 = 11 + ( rand() % 89 );
rand() % 89 will give you numbers [0, 88], so +11 would become [11, 99].
By the way, don't forget to srand( time( NULL ) ), otherwise it will (most probably) generate the same sequence of (pseudo) random numbers all the time.
( value % 100 ) is in the range 0 to 99. You add 11 so the range is in 11 to 110.
try something like this:
int random (int min,int max){
return min+(rand()%(max-min));
}
the arguments min and max indicate the range of the numbers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With