Adding Int

I currently have a code that will create random numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int i; // counter
	srand(time(NULL)); // seed random number generator
	// loop 10 times
	for (i = 1; i <= 10; i++) //i <=10, only select 10 numbers
    {
        // pick a random number from 1 to 100 and output it
		printf("%10d", 1 + (rand() % 100));

		// if counter is divisible by 1, begin a new line of output
		if (i % 5 == 0)
        {
			printf("\n");
		} // end if

	} // end for 

I would like to know how I can take the numbers that it generates and connect them into a variable. Such as if it was to come up with 12 as a number, then I would like for it to be able to be defined as an integer such as num1
well, it's possible (sort of). But I can't think of any situation in which it would be helpful.

All the code which would use the number afterwords would have to be couched in a bunch of conditional blocks, branched to by first testing the type. It seems like it'd be a huge hassle for no benefit.

if what you're looking for is a way to use the exact same name num1 for different types in the same code, then no it can't be done directly. It's possible you could make a template function which would take any numeric type and do all the work there. But why would you want to?
Last edited on
I am wanting to create random event occurrences in a game I am trying to make. I dont know how else i could do it.
1
2
3
4
int num;
num = rand(); //random event

//do what you want with num 
Okay. From what I had understood about rand() was that it would give you the same numbers if used repeatedly due to it not having different seeds. Thanks.
program 1:
1
2
3
int seed = 8;
srand(seed);
rand();  //e.g 101 


program 2:
1
2
3
int seed = 10;
srand(seed);
rand(); //e.g 300 


Program 1 and 2 produce different random numbers. But if they are run coninuesly, they will keep producing 101 and 300 respectively. This is coz, as long as the seed has not changed, the output will be the same.

So to keep the "seed" changing, we use time since "time" changes constantly.

1
2
3
4
5
#include <ctime>

int seed = time(0);
srand(seed);
rand();  //always different 


1
2
3
//better
srand(static_cast<unsigned>(time(NULL)));
rand();

Last edited on
I guess I misunderstood your first question. I thought you were wanting to create different variable types based on the value of the number generated.
The srand() should be called only on purpose (usually at beginning of the program). You should NOT call it every time you generate a number.
Something like this relieves you of having to worry about the seed in your main program
1
2
3
4
5
6
7
8
9
10
11
12
int GetRand( int min, int max )
{
	static bool initialized = false;

	if( !initialized )
	{
		// Seed the random-number generator with the current time 
		srand( (unsigned)time( NULL ) );
		initialized = true;
	}
	return (double)rand() / (RAND_MAX + 1) * ((max+1)- min) + min;
}
Topic archived. No new replies allowed.