我决定制作一个玩井字游戏的程序,但我用 if 语句失败了。它使用了我放在 else 下的任何内容。我已经盯着它看了两个小时了,我就是找不到任何不对劲的地方!这是代码:
#include <stdio.h>
#include <process.h>
int main()
{
char ans,ans2;
double a,b,c,d,e,f;
printf("Do you want to play? (y/n)\n"); //must make a loop
scanf ("%c",&ans);
if (ans == 'y')
{
printf("Do you want to be first?\n");
scanf ("%c",&ans2);
if (ans2 == 'y')
{
printf("Make your choice.\n");
printf(" 1 2 3\n");
printf("a | | \n");
printf(" - - -\n");
printf("b | | \n");
printf(" - - -\n");
printf("c | | \n");
}
else if (ans2 == 'n')
{
printf("option under construction!\n"); //must write this situation
}
else
printf("Invalid choice!\n");
}
else if (ans == 'n')
{
printf("Goodbye!\n");
system("pause");
}
else
printf("Invalid choice!\n");
}
请注意,该程序还没有完成(很明显)。
附言我昨天开始编程。
最佳答案
我猜,问题在于,当您使用 scanf
读取一个字符时,它会读取该字符,但您还输入了换行符。下一个 scanf
调用将读取该换行符而不是预期的字符。
最简单的解决方案是告诉 scanf
跳过空格(如换行符):
scanf(" %c", &ans);
注意 %c
之前的空格。
关于c - IF 语句不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15615798/