我的程序如下,我正在尝试在visual studio上运行它并且它一直给我一个错误Illegal if Without matching if
。
我相信它试图告诉我,我的else
与if
不符,但确实如此。以下是我的代码;有人可以运行它,让我知道问题是什么,所以我将来不再重复它了吗?
/* counting number of students that pass*/
#include <stdio.h>
main()
{
int pass, fail, grade;
printf(" This program tells you total number of students that passed\n Enter -1 to finish the program");
pass = 0;
fail = 0;
grade = 0;
while (grade != -1) { /* Enter -1 to finish the while loop*/
printf("Enter the grade of the student, 1 is pass, 2 is fail, -1 finishes the program\n");
scanf_s("%d", &grade);
if (grade == 1)
printf("The student passed\n");
pass = pass + 1; /* Add 1 to the pass*/
else if (grade == 2)
printf("The student failed\n");
fail = fail + 1; /*Add 1 to fail */
else
printf("You have entered an invalid number, please try again\n");
}
if (pass > 8)
printf("More than 8 students passed; raise tuition fees\n");
getchar();
}
答案 0 :(得分:2)
大括号是你的朋友。更改代码段
if (grade == 1)
printf("The student passed\n");
pass = pass + 1; /* Add 1 to the pass*/
else if (grade == 2)
printf("The student failed\n");
fail = fail + 1;
到
if (grade == 1){
printf("The student passed\n");
pass = pass + 1; /* Add 1 to the pass*/
}
else if (grade == 2){
printf("The student failed\n");
fail = fail + 1;
}
答案 1 :(得分:1)
if (grade == 1)
printf("The student passed\n");
pass = pass + 1;
代码pass = pass + 1;
不在if语句下,你需要多个语句的大括号:
if (grade == 1)
{
printf("The student passed\n");
pass = pass + 1;
}
else if (grade == 2)
{
printf("The student failed\n");
fail = fail + 1; /*Add 1 to fail */
}
答案 2 :(得分:0)
除非您使用大括号来定义if的开始和结束位置,否则语句pass = pass +1;
将在您的if之外:
if (grade == 1)
{
printf("The student passed\n");
pass = pass + 1; /* Add 1 to the pass*/
}
else if (grade == 2)