我的程序将乘客分配到飞机的座位上。我正在尝试使用goto语句,以便如果头等舱已满,它将乘客分配到经济舱。有一个提示询问他们是否要升入经济舱。我在这里放置了我最初的goto标签,并在经济舱之前贴上了以下标签。 goto语句可以工作,但是在调用之后它将停止整个程序。这是为什么?
https://repl.it/NFKf/7程序的链接。
#include < stdio.h >
int main(void) {
int airplaneSeats[10] = {0};
int firstClassCounter = 0;
int secondClassCounter = 0;
int picker;
char decision;
for (int i = 0; i < 10; ++i) {
printf("Press 1 for first class, 2 for economy class.\n");
scanf("%d", & picker);
if (picker == 1) {
++firstClassCounter;
if (airplaneSeats[0] != 1) {
++airplaneSeats[0];
printf("Your Boarding Pass: Seat 1 First Class\n\n");
} else if (airplaneSeats[1] != 1) {
++airplaneSeats[1];
printf("Your Boarding Pass: Seat 2 First Class\n\n");
} else if (airplaneSeats[2] != 1) {
++airplaneSeats[2];
printf("Your Boarding Pass: Seat 3 First Class\n\n");
} else if (airplaneSeats[3] != 1) {
++airplaneSeats[3];
printf("Your Boarding Pass: Seat 4 First Class\n\n");
} else if (airplaneSeats[4] != 1) {
++airplaneSeats[4];
printf("Your Boarding Pass: Seat 5 First Class\n\n");
}
* *
if (firstClassCounter == 5) {
printf("First Class is full.Do you want to be placed in economy? Enter 'Y' to be placed in economy,'N' to be placed on the next flight. \n");
scanf("%d", & decision);
if ('Y') {
goto secondClass;
} else {
printf("Next flight leaves in 3 hours.");
} * *
}
} else if (picker == 2) {
* * secondClass: * *
++secondClassCounter;
if (airplaneSeats[5] != 1) {
++airplaneSeats[5];
printf("Your Boarding Pass: Seat 6 Econonomy Class\n\n");
} else if (airplaneSeats[6] != 1) {
++airplaneSeats[6];
printf("Your Boarding Pass: Seat 7 Econonomy Class\n\n");
} else if (airplaneSeats[7] != 1) {
++airplaneSeats[7];
printf("Your Boarding Pass: Seat 8 Econonomy Class\n\n");
} else if (airplaneSeats[8] != 1) {
++airplaneSeats[8];
printf("Your Boarding Pass: Seat 9 Econonomy Class\n\n");
} else if (airplaneSeats[9] != 1) {
++airplaneSeats[9];
printf("Your Boarding Pass: Seat 10 Econonomy Class\n\n");
}
}
}
}
最佳答案
++airplaneSeats[n]
递增airplaneSeats
,而不是(airplaneSeats[n])
。
因此,它不是增加侧面airplaneSeats[n]
中的数字,而是增加airplaneSeats
指针以指向下一个元素。
请改用airplaneSeats[n]++;
。
关于c - goto语句提前结束程序的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46900666/