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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

intializing a variable to a random number 2

Status
Not open for further replies.

ssmitty

Programmer
Sep 5, 2002
9
0
0
US
I want to initialize a variable to a random number...something like this...

int somevariable = (random number between 1 - one hundred)...
i dunno...
 
srand(time(null));

int val = rand()%100 + 1;


you need to include time.h and I think the other include is either stdlib or stdio

Matt
 
oh wait, this gives me a random number, but it is the same everytime i run the program, is there one that changes the number each time i run the program?
 
You could just use any value on the stack.

int val;
val = val % 100;
 
the line,

srand(time(null));

should take care of the repeating number problem.

Matt
 
it could be useful to make a function that can generate random values for any number.

Code:
#include <time.h>
#include <stdlib.h>

Random( const int& ivalue )
{
	srand((unsigned)time( NULL ));

	if( ivalue == 0 )
	{
		return 0;
	}
	else 
	{
	    int random = rand() % ivalue;
	    return random;
	}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top