C Exercise 94
100 Classic C Language Examples
**Problem:** A guessing game.
**Analysis:** None.
Example
#include
<
stdio.h
#include
<
stdlib.h
#include
<
time.h// Handle the logic for whether to continue the game
int
ask_to_play_again
(
)
{
char
begin
;
printf
(
"
Do you want to challenge the highest level? Y/N
\
n
"
)
;
scanf
(
"
%c
"
, &
begin
)
;
// Note there is a leading space to skip the newline left by the previous input
if
(
begin
== '
Y
' ||
begin
== '
y
'
)
{
return
1
;
// The user chooses to continue the game
}
printf
(
"
Thank you, goodbye!
\
n
"
)
;
return
0
;
// The user chooses to quit the game
}
// The main logic of the game
void
caizi
(
void
)
{
int
n
;
int
count
=
1
;
srand
(
(
unsigned
int
)
time
(
NULL
)
)
;
// Handle the random number seed more rigorously
int
m
=
(
rand
(
)
%
100
)
1
;
printf
(
"
The game has started. Please enter a number:
\
n
"
)
;
while
(
1
)
{
scanf
(
"
%d
"
, &
n
)
;
if
(
n
==
m
)
{
printf
(
"
Guessed it! It took %d attempts!
\
n
"
,
count
)
;
// Give different feedback based on the number of guesses
if
(
count
==
1
)
{
printf
(
"
You are a god-level player! I worship you
\
n
"
)
;
}
else
if
(
count
<=
5
)
{
printf
(
"
You are a king-level player! Awesome
\
n
"
)
;
}
else
if
(
count
<=
10
)
{
printf
(
"
You are a master-level player! Amazing
\
n
"
)
;
}
else
if
(
count
<=
15
)
{
printf
(
"
You are a diamond-level player! Fantastic
\
n
"
)
;
}
else
{
printf
(
"
Your skills still need improvement!
\
n
"
)
;
}
// Ask whether to continue the game
if
(
ask_to_play_again
(
)
)
{
caizi
(
)
;
// Restart the game
}
break
;
}
else
if
(
n
<
m
)
{
puts
(
"Too small!
"
)
;
puts
(
"
Enter again:
"
)
;
}
else
{
puts
(
"
Too large!
"
)
;
puts
(
"
Enter again:
"
)
;
}
count
++;
// Counter
}
}
int
main
(
void
)
{
caizi
(
)
;
return
0
;
}
The above example produces the following output:
Game started, please enter a number:
50
太大了!
Re-enter:
25
太小了!
Re-enter:
40
太大了!
Re-enter:
30
太大了!
Re-enter:
27
太小了!
Re-enter:
28
猜中了,使用了 6 次!
你是大师级人物了!狂赞
需要挑战最高级别不?Y/N
N
谢谢,再见!