Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random Numbers

Status
Not open for further replies.

Stopher

Programmer
Jan 12, 2002
29
US
Is there an easy way to generate random integers? or doubles? or whatevers?

Thanx,
Da Stopher
 
Use rand function example given in msdn or one rerence which i gave in response to qs "Random number output to text file" here...anyway i repeat
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

int main(int argc, char* argv[])
{
int i;
FILE *fp;
fp=fopen(&quot;c:\\newtext.txt&quot;,&quot;w+&quot;);

/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );

/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
{
char szTemp[64];
printf( &quot; %6d\n&quot;, rand() );
_itoa(rand(),szTemp,10);
strcat(szTemp,&quot; &quot;);
fputs(szTemp,fp);
}
fclose(fp);
return 0;
}
hope it helps
 
To elaborate, a call to rand() generates psuedo-random numbers, or &quot;random&quot; numbers that follow a mathmatical pattern. This, of course, isn't truly random, so a &quot;seed&quot; is thrown in to change the pattern of rand() to appear not so random. srand() accmoplishes this, and by passing an ever-changing arguement like system time to srand ( srand( time( 0 ) ) ) you get the effect of actual random numbers.

rand() &quot;returns a value between(inclusive) 0 and and RAND_MAX (defined by the compiler, often 32767). &quot; so to get a random number between a certain range say 0-10, you need to use the modulus operator to shrink the range: rand() % 11. If you want to get a random number between, say 5 and 15 you simply do as above, but use an offset ( 5 in this case so... rand % 11 + 5 ).
 
That did the trick...thanx guys ;)

Thanx,
Da Stopher
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top