多年来,我一直坚持着同样的几种语言,于是我决定学习C。
我已经写了一个猜数游戏,它根据难度水平生成一个随机数,然后你会有5次猜测这个数字的尝试。
如果你猜错了,它会告诉你答案是高还是低,这会给你一个线索。我发现这个游戏很有交互性,我想得到一个代码审查,看看我如何改进它。
这是我的第一个C程序,我只是想改进。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int generate_random_number(int min, int max) {
srand ( time(NULL) );
return min + (rand() % (max - min));
}
void play() {
int difficulty = 1; // 1 = easy, 2 = medium, 3 = hard, 4 = insane
printf("1 = EASY, 2 = MEDIUM, 3 = HARD, & 4 = INSANE\n");
printf("What level would you like to play: ");
scanf("%i", &difficulty);
int min = 0;
int max = 0;
int random = 0;
if (difficulty == 1) {
min = 0;
max = 25;
printf("You have selected to play easy\n\n");
}
else if (difficulty == 2) {
min = 0;
max = 50;
printf("You have selected to play medium\n\n");
}
else if (difficulty == 3) {
min = 0;
max = 75;
printf("You have selected to play hard\n\n");
}
else if (difficulty == 4) {
min = 0;
max = 100;
printf("You have selected to play insane\n\n");
}
random = generate_random_number(min, max);
int tries = 5;
int won = 0;
while (tries > 0)
{
int guess = 1000000; // just so it doesn't accidentally equal to random
printf("Guess a number %i to %i: ", min, max);
scanf("%i", &guess);
if (guess == random) {
won = 1;
break;
}
else {
if (guess > random) {
printf("Incorrect guess, the answer is lower than your guess!\n\n");
}
else {
printf("Incorrect guess, the answer is higher than your guess!\n\n");
}
}
tries -= 1;
}
if (won) {
printf("Congratulations, you have won the game!");
}
else {
printf("Sorry, you are out of tries.\n\n");
}
}
int main() {
while (1) {
play();
}
return 0;
}
发布于 2020-03-18 17:27:15
int generate_random_number(int min,int max) { srand (空);返回min + (rand() % (max - min));}
您应该只在main
开始时为随机数生成器添加一次种子。在这种情况下,如果(由于某种原因)某人在一秒钟内玩了不止一轮,那么两场比赛的号码都是一样的。对于这个特定的程序来说,可能不是一个大问题,但是需要注意一些事情。
发布于 2020-03-18 08:04:44
如果(困难== 1) {如果(困难== 2) {如果(困难== 3) {
这看起来像switch (difficulty)
可能更合适--也许使用default
分支来捕获超出范围的值。
或者,更简单地说,由于我们只是选择值,而且min
总是为0,所以只需从数组值中选择(在验证用户的选择在范围内之后):
int max[] = { 25, 50, 75, 100 };
实际上,使用这些值,我们可以简单地乘以:
int max = 25 * difficulty;
扫描(“%i”,及困难);
不要仅仅丢弃scanf()
的结果--总是测试它转换了多少值。在这种情况下,
if (scanf("%i", &difficulty) != 1) {
fputs("Enter a number!\n", stderr);
exit(EXIT_FAILURE); /* or some better handling */
}
同样,这里:
scanf("%i", &guess);
最后,允许用户在厌倦游戏时退出游戏是礼貌的(我知道,我也不敢相信会发生这种事!)
https://codereview.stackexchange.com/questions/239103
复制