Keep in mind that the program takes the role of the one guessing the number, whi
ID: 641061 • Letter: K
Question
Keep in mind that the program takes the role of the one guessing the number, while the user provides the answers to the questions that the program is going to ask. The user will answer with one-character input, i.e. either 'y' or 'n'. After the necessary number of questions the program needs to come up with the number.
Hint: the one character input is tricky. As we read the input from the command line, which is automatically buffered, you need to hit the return key in order to make the system to actually stop reading and look at the input. Thus, automatically you get a extra, unwanted ASCII 10 (i.e. new line) character, that you need to get rid of. In addition to using fflush or putting a extra space in the scanf you could also use the getchar() function and call the function twice. The second getchar() call will just discard the excess character:
response = getchar(); getchar();
In the above example, getchar() reads one character and puts it into the variable response (type char), then tries to read another character, catching the new line char that you entered before as well, thus discarding it.
note********** in C LANGUAGE
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int main(void) {
srand(time(NULL));
int r = rand() % 10 + 1;
bool correct = false;
int guess;
int counter = 0;
while(!correct)
{
printf("Guess my number! ");
scanf("%d", &guess);
getchar();
if (guess < r) {
printf("Your guess is too low. Guess again. ");
}
else if (guess > r) {
printf("Your guess is too high. Guess again. ");
}
else /* if (guess == r) */ {
printf("You guessed correctly in %d tries! Congratulations! ", counter);
correct = true;
}
counter++;
} /* while(!correct) */
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.