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?
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 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