我是C的新手,我在C中找到了一个论坛,用于结束一个while循环,而且一个没有真正帮助,因为它仍然不起作用。它给了我一个预期的;在休息之前"或" int keep_playing = 4"结束循环。这是一个简单的石头剪刀游戏,我只是在循环工作,很快就会担心逻辑部分。这是我的代码。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
printf("Welcome to rock paper scissors!\n");
int keep_playing=5;
while (keep_playing==5)
printf("Press 'y' to play or 'n' to quit: ");
char playornot;
scanf("%c\n",&playornot);
if (playornot=='y')
printf("Ok.\n");
else (playornot=='y')
int keep_playing=4;
return 0;
}
答案 0 :(得分:2)
您有两个基本问题:
答案 1 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
printf("Welcome to rock paper scissors!\n");
int keep_playing=5;
while (keep_playing==5) {
printf("Press 'y' to play or 'n' to quit: ");
char playornot;
scanf("%c",&playornot);
if (playornot=='y') {
printf("Ok.\n");
} else if (playornot=='n') {
keep_playing=4;
}
}
return 0;
}
您的代码应该如何。在你的情况下,有一个无限循环,因为唯一重复的行是printf("Press 'y' to play or 'n' to quit: ");
。这是由花括号的运气造成的。
然后,你会说错字 - int
中的多余int keep_playing=4
。这声明了另一个变量,仅在此范围内可见。实际上它应该在没有花括号时引起错误,因为那时的范围是相同的。
还有第三个错误,之前没人提到过。如果输入的字符不是y
,那么它应该是n
。否则你应该要求另一个输入或以某种方式决定如何处理它。
第四个是你试图将两个字符扫描到char playornot
。已从\n
移除了scanf
。