C Exercise Example 94
Title:Guessing game.
Program analysis:None.
Example
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Handle the logic of 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 the space at the beginning to ensure skipping the newline from the previous input
if (begin == 'Y' || begin == 'y') {
return 1; // User chooses to continue the game
}
printf("Thank you, goodbye!\n");
return 0; // User chooses to exit the game
}
// 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("Game start, please enter a number:\n");
while (1) {
scanf("%d", &n);
if (n == m) {
printf("You guessed it! It took %d tries!\n", count);
// Give different feedback based on the number of guesses
if (count == 1) {
printf("You are a god-level person! Worship!\n");
} else if (count <= 5) {
printf("You are a king-level person! Very impressive!\n");
} else if (count <= 10) {
printf("You are a master-level person! Highly praised!\n");
} else if (count <= 15) {
printf("You are a diamond-level person! Tremendous praise!\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("Re-enter:");
} else {
puts("Too big!");
puts("Re-enter:");
}
count++; // Counter
}
}
int main(void) {
caizi();
return 0;
}
The output of the above example is:
游戏开始,请输入数字: 50 太大了! 重新输入: 25 太小了! 重新输入: 40 太大了! 重新输入: 30 太大了! 重新输入: 27 太小了! 重新输入: 28 猜中了,使用了 6 次! 你是大师级人物了!狂赞 需要挑战最高级别不?Y/N N 谢谢,再见!other extensions