[英]Else if statement in C not working as expected
My program is below, i'm trying to run it on visual studio and it keeps giving me an error Illegal if Without matching if
. 我的程序在下面,我试图在Visual Studio上运行它,但Illegal if Without matching if
,它将不断给我一个错误提示。
I believe it is trying to tell me that my else
doesn't match my if
, but it does. 我相信它试图告诉我我的else
与if
不匹配,但是确实如此。 Below is my code; 下面是我的代码; can someone run it and let me know what the problem is so I don't repeat it in the future? 有人可以运行它并让我知道问题出在哪里,以便将来不再重复?
/* 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();
}
Braces are your friends. 大括号是您的朋友。 Change the snippet 更改代码段
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;
to 至
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;
The code pass = pass + 1;
代码pass = pass + 1;
is not under the if statement, you need braces for multiple statements: 不在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 */
}
The statement pass = pass +1;
语句pass = pass +1;
will be outside your if unless you use braces to define where your if starts and ends: 除非您使用花括号定义if的开始和结束位置,否则它将在if之外:
if (grade == 1)
{
printf("The student passed\n");
pass = pass + 1; /* Add 1 to the pass*/
}
else if (grade == 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.