我刚学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 Salah”,然后自动再次打印一次“请输入您的分数:Nilai Anda Salah”。之后再次打印“请输入您的分数:”,然后我可以再次输入分数。
我不知道为什么它跳过 scanf 命令。
最佳答案
使用以下格式说明符
scanf(" %c", &score);
^^^
跳过输入字符之间的新行字符。
另外,根据 C 标准,不带参数的 main 函数应声明如下
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;
}
关于c - 使用 goto 控制语句进行循环,但它会跳过一个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43570817/