我刚刚学习了C编程。现在,我正在尝试执行循环使用 goto 控制语句,但是当我时我遇到了问题使用变量 char 。
#include <stdio.h>
char score;
int main(){
loop:
printf("Please Input Your Score : ");
scanf("%c", &score);
switch(score){
case 'A' :
printf("Nilai Anda Baik");
break;
default :
printf("Nilai Anda Salah");
goto loop;
}
return 0;
}
问题是,如果我输入错误的分数,例如'b',它将打印" nilai anda anda salah",然后自动再次打印"请输入您的分数:nilai anda anda salah"一次。再次打印后"请输入您的分数:",然后我可以再次输入分数。
我不知道为什么它跳过 scanf 命令。
使用以下格式指定器
scanf(" %c", &score);
^^^
跳过输入字符之间的新系列字符。
同样根据C标准函数主,无参数称为
int main( void )
考虑使用goto
语句是一个坏主意。另外,无需将变量score
声明为全局。
该程序可以看起来以下方式
#include <stdio.h>
int main(void)
{
char score = 'A';
do
{
printf( "Please Input Your Score : " );
scanf( " %c", &score );
switch( score )
{
case 'A' :
puts( "Nilai Anda Baik" );
break;
default :
puts( "Nilai Anda Salah" );
break;
}
} while ( score != 'A' );
return 0;
}