Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random function in C

Tags:

c

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?

like image 408
user1601731 Avatar asked Dec 08 '22 21:12

user1601731


2 Answers

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.

like image 68
Kiril Kirov Avatar answered Dec 26 '22 22:12

Kiril Kirov


( 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

like image 41
Maarten Blokker Avatar answered Dec 26 '22 23:12

Maarten Blokker