文曲星猜数游戏c语言函数结构
时间: 2023-07-09 22:53:31 浏览: 202
以下是一个简单的文曲星猜数游戏的C语言函数结构示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void play_game() {
int guess, num_attempts = 0;
int secret_num = rand() % 100 + 1;
printf("Welcome to the Guessing Game!\n");
printf("I'm thinking of a number between 1 and 100.\n");
while (1) {
printf("Enter your guess: ");
scanf("%d", &guess);
num_attempts++;
if (guess == secret_num) {
printf("Congratulations, you guessed it!\n");
printf("You took %d attempts.\n", num_attempts);
break;
} else if (guess < secret_num) {
printf("Too low, try again!\n");
} else {
printf("Too high, try again!\n");
}
}
}
int main() {
srand(time(0));
char play_again = 'y';
while (play_again == 'y') {
play_game();
printf("Would you like to play again? (y/n) ");
scanf(" %c", &play_again);
}
printf("Thanks for playing!\n");
return 0;
}
```
该示例包含两个函数:`play_game()` 和 `main()`。
`play_game()` 函数实现了猜数游戏的逻辑,包括生成随机数、提示玩家输入猜测、判断猜测是否正确等。
`main()` 函数则实现了游戏的整体流程,包括初始化随机数种子、循环播放游戏、询问玩家是否再次玩游戏等。
阅读全文