this in same code the task 3 You may have noticed that, rand() is not random at
ID: 3572238 • Letter: T
Question
this in same code the task 3
You may have noticed that, rand() is not random at all, it will always produce a specific number when you run your guessing game. Modify your guessing.c, named the new game guessing2doto.c. Version 2 of the guessing game will have the following improvements: Add srand(time(NULL)); instruction before generating a random number to increase the randomness of rand() Before terminating, print out a message to indicate that the time is up. You will need to create a customized handler for SIGALRM, and use signal() system call to catch it. Your program should work like this:Explanation / Answer
#include<stdio.h>
#include<signal.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, n;
time_t t;
void display_message();
//install signal handler for sigalarm
signal(SIGALRM, display_message);
/* Intializes random number generator */
srand((unsigned)time(&t));
//generate number n below 10
n = rand() % 10;
//call alarm to set up time
alarm(8);
printf("Guess a number from 1-10 : ");
while (1)
{
scanf("%d", &i);
if (i == n)
{
printf("You got it! ");
break;
}
printf("Guess again: ");
}
}
//function which will be called when time up
void display_message(int signo)
{
if (signo == SIGALRM)
{
printf(" You ran out of time, bye bye! ");
exit(1);
}
}
-----------------------------------------------------------------------------
output1:
Guess a number from 1-10 : 5
Guess again: 6
Guess again: 7
Guess again: 8
Guess again: 2
You got it!
output2:
Guess a number from 1-10 : 2
Guess again: 3
Guess again: 4
Guess again: 5
Guess again:
You ran out of time, bye bye!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.