使用If语句的简单C程序停止在VS代码中运行



我制作了一个简单的C程序来理解If Else语句的工作,但在VS Code中,程序在第二次输入时停止,没有任何错误提示。请告诉我我的程序有什么问题?我是编程初学者。

#include <stdio.h>
int main(){
char math, sci;
printf("Have you passed Mathematics test (y/n)n");
scanf("%c", &math);
printf("Have you passed Science test (y/n)n");
scanf("%c", &sci);
if ((math == 'y') && (sci == 'y'))
{
printf("You get a gift of worth Rs. 45.");
}
else if ((math == 'n') && (sci == 'y'))
{
printf("You get a gift of worth Rs. 15.");
}
else if ((math == 'y') && (sci == 'n'))
{
printf("You get a gift of worth Rs. 15.");
}
else if ((math == 'n') && (sci == 'n'))
{
printf("You don't get any gift.");
}
return 0;
}

第二个scanf()读取第一个scanf()stdin中挂起的换行符。

在转换字符串中使用带有初始空格的scanf(" %c", &sci);来消耗输入中的任何换行符和初始空白。同时测试scanf()的返回值,以检测文件的提前结束。

这是修改后的版本:

#include <stdio.h>
int main() {
char math, sci;
printf("Have you passed Mathematics test (y/n)n");
if (scanf(" %c", &math) != 1) {
printf("Missing inputn");
return 1;
}
printf("Have you passed Science test (y/n)n");
if (scanf(" %c", &sci) != 1) {
printf("Missing inputn");
return 1;
}
if ((math == 'y') && (sci == 'y')) {
printf("You get a gift of worth Rs. 45.n");
} else
if ((math == 'n') && (sci == 'y')) {
printf("You get a gift of worth Rs. 15.n");
} else
if ((math == 'y') && (sci == 'n')) {
printf("You get a gift of worth Rs. 15.n");
} else
if ((math == 'n') && (sci == 'n')) {
printf("You don't get any gift.n");
} else {
printf("Invalid input.n");
}
return 0;
}

您只需更改

scanf("%c",&math(到scanf("%c",&sci(

scanf("%c",&sci(到scanf("%c",&math(

#include <stdio.h>
int main(){
char math, sci;
printf("Have you passed Mathematics test (y/n)n");
scanf(" %c", &math);
printf("Have you passed Science test (y/n)n");
scanf(" %c", &sci);
if ((math == 'y') && (sci == 'y'))
{
printf("You get a gift of worth Rs. 45.n");
}
else if ((math == 'n') && (sci == 'y')||(math == 'y') && (sci == 'n'))
{
printf("You get a gift of worth Rs. 15.n");
}
else if ((math == 'n') && (sci == 'n'))
{
printf("You don't get any gift.n");
}
return 0;
}

最新更新