Ví dụ chạy chương trình (trường hợp người chơi thắng):
Ví dụ chạy chương trình (trường hợp người chơi thua):
What is your name? Phi
Hello Phi. I'm thinking of a number between 1 and 20. Could you make a guess?
Make a guess: 5
That's too low!
Make a guess: 10
That's too high!
Make a guess: 8
That's too high!
Make a guess: 6
Good job! You guessed my number in 4 guesses!
What is your name? Phi
Hello Phi. I'm thinking of a number between 1 and 20. Could you make a guess?
Make a guess: 5
That's too low!
Make a guess: 5
That's too low!
Make a guess: 5
That's too low!
Make a guess: 5
That's too low!
Make a guess: 5
That's too low!
Nope! The number I was thinking of was 9!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define NAME_LEN 20
int main()
{
char name[NAME_LEN];
srand(time(0));
int secretNumber = rand() % 20 + 1;
printf("What is your name? ");
fgets(name, NAME_LEN, stdin);
strtok(name, "\n");
printf("Hello %s. I'm thinking of a number between 1 and 20. Could you make a guess?", name);
int answer;
int guesses = 0;
do {
++guesses;
printf("\nMake a guess: ");
scanf("%d", &answer);
if (answer < secretNumber)
printf("That's too low!");
else if (answer > secretNumber)
printf("That's too high!");
else
break;
} while (guesses < 5);
if (answer == secretNumber)
printf("\nGood job! You guessed my number in %d guesses!", guesses);
else
printf("\nNope! The number I was thinking of was %d!", secretNumber);
return 0;
}