【发布时间】:2014-03-11 07:31:53
【问题描述】:
我正在制作一个猜数字游戏程序,但我的 else 语句遇到了一些问题。在试图猜测数字的主块中,if 和 if else 语句有效,但 else 语句不执行任何操作。我试图让它在范围之外的数字 0
此外,如果输入“1”,我会尝试让游戏重演,但无论输入什么,程序都会崩溃。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/*Number guessing game: The number that needs to be guessed is 52*/
int guess;
int attempt = 6;
int playAgain = 1;
printf("Guess the integer that I am thinking of between 1 and 100\n");
printf("I will tell you if you guess too high or too low\n");
printf("You have 6 attempts\n");
printf("What is your first guess?\n");
if (playAgain == 1)
{
while (attempt > 0)
{
scanf_s("%d", &guess);
if (guess > 0)
{
if (guess < 52)
{
attempt--;
printf("Sorry! Too low! You have %d more tries:\n", attempt);
}
}
else if (guess <100)
{
if (guess > 52)
{
attempt--;
printf("Sorry! Too high! You have %d more tries:\n", attempt);
}
}
else if (guess == 52)
{
printf("Correct! You win!\n");
attempt = 0;
}
else
{
printf("Invalid input: Please enter an integer between 1 and 100:\n");
}
}
printf("Enter '1' to play again or anything else to terminate\n");
scanf_s("%d", playAgain);
attempt = 6;
}
else
{
printf("Thanks for playing!\n");
}
return 0;
}
【问题讨论】:
-
为了您自己的理智,请使用一致的编码风格并始终以相同的方式缩进。如果您使用 tab 键缩进,请确保代码编辑器正在插入 空格。
-
另外,在你学习的时候,为 every if/else 使用大括号。这(加上这样的缩进)应该有助于澄清代码的含义。
-
你创建了另外两个,但只有一个可以使用开关盒或类似的东西
-
如果您在执行上述两个建议后仍有问题 - 请告诉我们。这很可能足以让您找出问题所在。
标签: c if-statement