119k views
5 votes
The program below generates a random number and prints it out. However, the same random number vill be obtained each time you run the program. Please run the program twice to confirm this. Modify the program so that the program generates a different random number each time you run the rogram. \#include "stdio.h" \#include "stdlib.h" void main(void) { int rand1; srand(997); rand1 = rand(); printf("The number is \%d \\", rand1); Modify the program in the last exercise so that the program generates a different random number in he range of 30∼90 each time you run the program. Run your program at least twice to test your rogram.

User CAdaker
by
7.8k points

1 Answer

0 votes

Final answer:

To generate different random numbers each time, replace the constant seed value in the srand() function with the current time and adjust the range of the random number to be between 30 and 90.

Step-by-step explanation:

The current program generates the same random number each time because it uses a constant seed value of 997 with the srand() function. To have the program generate a different random number each time, we need to provide a different seed value. The common approach is to use the current time as a seed, which changes every second. Therefore, we should include the time.h header and modify the call to srand() like so: srand((unsigned)time(NULL)). After introducing this change, we can adjust the range of the random numbers to be between 30 and 90 by modifying the assignment to rand1 as follows: rand1 = (rand() % 61) + 30;. The % 61 ensures the number is between 0 and 60, and adding 30 shifts the range to 30-90.

User Iamsamstimpson
by
8.1k points