I am a complete beginner in C and I'm sorry in advance for a trivial question. Q: I would like to return the value of random_num variable that is calculated in number_generator function to the main function:
int main() //didn't paste headers and prototype
{
int random_num; // <= to here
number_generator(random_num);
printf("random number: %d", random_num);
return 0;
}
int number_generator(int random_num)
{
srand(time (0));
random_num = (rand() % 100) + 0; // <= return value from here
}
Currently, the terminal output of printf is 0 while it should be in a range from 0 to 100.
Do it the following way
int number_generator(void )
int main() //didn't paste headers and prototype
{
int random_num = number_generator(); // <= to here
printf("random number: %d", random_num);
return 0;
}
int number_generator(void )
{
srand(time (0));
return (rand() % 100) + 0; // <= return value from here
}
Another approach is the following
void number_generator(int *random_num);
int main() //didn't paste headers and prototype
{
int random_num; // <= to here
number_generator( &random_num);
printf("random number: %d", random_num);
return 0;
}
void number_generator(int *random_num)
{
srand(time (0));
*random_num = (rand() % 100) + 0; // <= return value from here
}
Pay attention to that adding 0 in this expression
(rand() % 100) + 0
does not make a sense. It is equivalent to
(rand() % 100)