-
random integers
hi this is my first time to visit this site hope some1 can help me
how to generate a random integers in a given range say from is nto a problem for me but the problem is who to get more than one integer (ie the code i used only gives me one integer how can i get n number of integers )
this is my code
int range,num,r,i ;
{
printf("Enter the range size(max=20)");
scanf("%d",&range);
printf("How many numbers do you wish to generate?");
scanf("%d",&num);
date_time_seed();
r=1+rand()%range;
}
printf("%d\n",r);
return(0);
}
i think it is to do with for loop but i dunno who to do it using the input num
can any1 help plz
-
Try a for-loop.
Code:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int range,num,r,i ;
printf("Enter the range size(max=20)");
scanf("%d",&range);
printf("How many numbers do you wish to generate?");
scanf("%d",&num);
srand((unsigned) time(NULL));
for (i=0; i<num; i++)
{
r=1+rand()%range;
printf("%d\n",r);
}
return(0);
}
-
The way I have always used is:
srand ( time(0) );
var = (int) (rand() / (RAND_MAX + 1.0) * (high - low + 1);
Example:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int randnum, high, low, num, i;
srand( time(0) );
printf("Please enter the range (example 1 - 20): ");
scanf("%d - %d",&low,&high);
printf("\nHow many number do you wish to get?: ");
scanf("%d",&num);
for (i = 0;i < num;i++)
{
randnum = (int) (rand() / (RAND_MAX + 1.0) * (high - low + 1) + low);
printf("\n%d",randnum);
}
return 0;
}