//
// Created by hengxin on 9/23/22.
//
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
int high = 100;
int number_of_tries = 7;
/*
* print the rules of the game to players
*/
printf("Let us play the Guess the Number game.\n"
"The computer will generate a number between 1 and %d.\n"
"You have %d tires.\n", high, number_of_tries);
/*
* generate a random number between 1 and high as the secret number
*/
srand(time(NULL));
int secret = rand() % high + 1;
/*
* ask the player to input a guess
*/
/*
* obtain the guessed number,
* compare it with the secret number,
* and inform the player of the result
*/
while (number_of_tries > 0) {
printf("Please input your guess.\n"
"You still have %d tries.\n", number_of_tries);
int guess = 0;
scanf("%d", &guess);
printf("Your guess is %d.\n", guess);
if (guess == secret) {
printf("You Win!\n");
break;
} else if (guess > secret) {
printf("guess > secret\n");
} else {
printf("guess < secret\n");
}
/*
* repeat (3)-(4) until the player wins or loses
*/
number_of_tries--;
/*
* TODO: I have left at least one bug in this program.
* Can you find it (first in natural languages)?
* Can you fix it (in C language)?
*/
}
return 0;
}
这段代码是一个简单的猜数字游戏程序。现在我来对代码进行解读:
1.首先,代码中使用了stdio.h、time.h和stdlib.h这三个头文件。stdio.h提供了输入输出函数,time.h提供了时间相关函数,stdlib.h提供了随机数生成函数。
2.在main()函数中,定义了两个变量high和number_of_tries,分别表示随机数的上限和玩家可猜测的次数。
3.使用printf()函数打印游戏规则给玩家,显示了游戏的玩法和规则。
4.使用srand(time(NULL))函数结合当前时间设置随机数种子,然后使用rand()函数生成一个随机数,并对其进行取余运算得到1到high之间的一个随机数,将其赋值给变量secret作为秘密数字。
5.进入一个while循环,只要number_of_tries大于0,就继续执行下面的代码块。
6.在循环中,使用printf()函数提示玩家输入猜测的数字,并显示还有多少次猜测机会。
7.使用scanf()函数接收玩家输入的猜测数字,并将其存储在变量guess中。
8.使用printf()函数显示玩家猜测的数字。
9.使用条件语句判断玩家的猜测是否和秘密数字相等,如果相等,输出"You Win!",并通过break语句跳出循环。
10.如果猜测数字大于秘密数字,使用printf()函数输出"guess > secret";如果猜测数字小于秘密数字,使用printf()函数输出"guess < secret"。
11.在循环的最后,将number_of_tries减1,表示玩家的猜测机会减少一次。
12.最后返回0,表示程序运行结束。
至于代码中存在的bug,由于代码没有进行错误处理,如果玩家输入非整数的内容,程序会出现错误。为了解决这个问题,可以在接收玩家输入的地方进行输入合法性的判断,如果输入非整数,则提示玩家重新输入。另外,代码还可以在适当的地方添加注释,以提高代码的可读性和可维护性。