Trying to create a function that generates a random number using rand()
and srand()
.
This code prints 3 random numbers successfully:
//prints a random number from 1 to 10 3 times.
void main()
{
int num;
srand(time(NULL));
num = rand() % 10;
printf("%d\n", num);
num = rand() % 10;
printf("%d\n", num);
num = rand() % 10;
printf("%d\n", num);
}
//Output: 3 5 6
This code using a function doesn't:
//calls PrintRandomNumber 3 times.
void main()
{
int i=0, num;
for(i=0; i<3; i++)
{
printRandomNumber(0, 10);
}
}
//Prints a random numberin the range of lowestValue to highestValue.
void printRandomNumber(int lowestValue, int highestValue)
{
int randomNumber = 0;
srand(time(NULL));
randomNumber = (rand() % (highestValue - lowestValue + 1)) + lowestValue;
printf("%d\n", randomNumber);
}
//Output: 3 3 3
The problem is calling srand(time(NULL))
multiple times.
Can a function print/return a random number using rand()
and srand()
without having to call srand(time(NULL))
in the main?