C Language - Generate random values

August 2017



Issue


I want to generate a number between 0 and 4 (possible values: 0,1,2,3,4) that will be then stored in the "nbr" variable.
  • How to achieve the following using the rand () function?

Solution


Try this:
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#include <conio.h> 

int Random (int _iMin, int _iMax) 
{ 
return (_iMin + (rand () % (_iMax-_iMin+1))); 
} 

int main (void) 
{ 
int iRandom; 

srand (time (NULL)); 
iRandom = Random (50,100); 
printf ("Random : %d", iRandom); 
getch(); 
return 0; 
} 


Thanks to scoubidou944 for this tip.

Related


Published by deri58. Latest update on October 17, 2012 at 09:01 AM by deri58.
This document, titled "C Language - Generate random values," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).