I am learning how to use "rand()" and "srand()" in C. In the book that I am reading, it asks to modify a program that generates random numbers so that the user supplies a seed. This ensures the numbers are random. I am able to generate new numbers using the basic code directly below, but it will not work when I try to use it within the program beneath it.
int main()
{
int seed;
srand(seed);
printf("Please enter a seed: ");
scanf("%d", &seed);
printf("The random number is: %d\n", rand());
return (EXIT_SUCCESS);
}
Here is the program I am having trouble getting "srand() to work in below. I have tried asking the user for the seed in "main", rather than the prn_random_numbers function and everything else I could think of. It still only behaves like "rand()" and spits out the same number regardless of the seed that I enter. What am I doing wrong? Unfortunately, the book doesn't give any answers to the exercises. I greatly appreciate any help. I am just learning on my own.
max(x, y)
int x, y;
{
if (x > y)
return (x);
else
return (y);
}
min(x, y)
int x, y;
{
if (x < y)
return (x);
else
return (y);
}
prn_random_numbers(k) /* print k random numbers */
int k;
{
int i, r, smallest, biggest;
int seed;
srand(seed);
printf("Please enter a seed: ");
scanf("%d", &seed);
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 1; i < k; ++i)
{
if (i % 5 == 0)
printf("\n");
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main()
{
int n;
printf("Some random numbers are to be printed.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
while (n < 1)
{
printf("ERROR! Please enter a positive integer.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
}
prn_random_numbers(n);
return (EXIT_SUCCESS);
}