Connecting Tech Pros Worldwide Forums | Help | Site Map

random

Member
 
Join Date: Jun 2006
Posts: 57
#1: Sep 4 '06
How Can I random two digits?????

Please help me!!!!!!

Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,185
#2: Sep 4 '06

re: random


I think you have some words missing from that question :D

However the C standard library provides 2 routines for getting random values

srand - this seeds the random number generator, often called as

srand(time(NULL));

rand - this returns a value bwteen 0 and RAND_MAX, you will need to scale the return value to the range you require.
Member
 
Join Date: Jun 2006
Posts: 57
#3: Sep 4 '06

re: random


But I need only two digits for example:

sometimes it shows 35 and sometimes it shows 45
D_C D_C is offline
Needs Regular Fix
 
Join Date: Jun 2006
Posts: 294
#4: Sep 4 '06

re: random


Then make the range from 00 to 99, i.e. multiply the random value by 100, or take it modulo 100, depending on the range of the random value.
Member
 
Join Date: Jun 2006
Posts: 57
#5: Sep 5 '06

re: random


Quote:

Originally Posted by D_C

Then make the range from 00 to 99, i.e. multiply the random value by 100, or take it modulo 100, depending on the range of the random value.


Can You Give Me The Source?
Newbie
 
Join Date: Aug 2006
Posts: 10
#6: Sep 5 '06

re: random


hi
may be this will help u out

/* rand example */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
/* initialize random generator */
srand ( time(NULL) );

/* generate some random numbers */
printf ("A number between 0 and RAND_MAX (%d): %d\n", RAND_MAX, rand());
printf ("A number between 0 and 99: %d\n", rand()%100);
printf ("A number between 20 and 29: %d\n", rand()%10+20);

return 0;
}

Output:
A number between 0 and RAND_MAX (32767): 30159
A number between 0 and 99: 72
A number between 20 and 29: 23


A good way to generate almost-true random numbers is to initialize the random algorithm using srand with the current time in seconds as parameter, as obtained from time function included in <time.h>.
And, generally, a good way to get an integer random number between a range is to perform a module (%) operation on a result provided by rand():

thus rand()%25 would be a random number between 0 and 24, both included.
Reply