gpt4 book ai didi

c - C 中的 else if 语句未按预期工作

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:54 25 4
gpt4 key购买 nike

我的程序在下面,我试图在 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();
}

最佳答案

大括号是你的 friend 。更改代码段

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;
}

关于c - C 中的 else if 语句未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34979989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com