Random function in C

I need a random function for betwen numbers 11 and 99. I wrote this:

int random (void){ int i2; i2=11+(rand()%99); return i2; } 

but numbers exceed 99. Why?

+4
source share
3 answers

Because if rand() return 98 , then 98 % 99 is 98 and 98 + 11 > 99 .

For this you need

 i2 = 11 + ( rand() % 89 ); 

rand() % 89 will give you the numbers [0, 88] , so +11 will become [11, 99] .


By the way, do not forget srand( time( NULL ) ) , otherwise it (most likely) will generate the same sequence of (pseudo) random numbers all the time.

+11
source

(value% 100) is in the range of 0 to 99. You add 11 so that the range is in the range of 11 to 110.

try something like this:

 int random (int min,int max){ return min+(rand()%(max-min)); } 

arguments min and max indicate a range of numbers

+2
source

Because rand()%99 returns a value from 0 to 98; then you add 11, so the range is from 11 to 109. You should change 99 with 89

+1
source

All Articles