【发布时间】:2020-07-06 05:27:50
【问题描述】:
我的 for 循环开关无法工作。如果用户键入除“y”、“Y”、“n”、“N”以外的字母,我希望程序重复该问题。有人可以帮我解决吗?
#include <stdio.h>
int main(void) {
int flag = 0;
char mstatus;
printf("Are you married?\n");
scanf(" %c", &mstatus);
for (; flag == 1;) {
printf("Are you married?\n");
scanf(" %c", &mstatus);
switch (mstatus) {
case 'y':
case 'Y':
printf("You have answer yes for married");
flag = 1;
break;
case 'n':
case 'N':
printf("You have answer no for married");
flag = 1;
break;
default:
printf("please re-enter a valid answer");
scanf(" %c", &mstatus);
}
}
return 0;
}
【问题讨论】:
-
循环未启动。将标志初始化为 1
-
while循环或do...while循环会更清晰。你的条件不对。使用for(; flag == 0; )或更好的while(flag == 0)或do { ... } while(flag == 0); -
只需将
flag == 1更改为flag != 1。 -
使用调试器并单步执行代码。你会很快找到你所有的错误。调试是编码的重要组成部分。
-
测试出来的错误,为什么循环前的第一对printf/scanf?不使用第一个 scanf 输入。另外为什么 scanf 进入 switch 的“默认”情况?未使用输入字符
标签: c for-loop switch-statement