使此程序分配座位和循环时遇到问题



如果无法让此代码打印1个座位,则返回到用户提示。它应该循环返回,直到座位坐满,然后显示头等舱/经济舱已满。这是我目前掌握的代码。

int main(int argc, char** argv) {
const int firstClass[] = {1, 2, 3, 4}; //first class array list
const int economyClass[] = {5, 6, 7, 8, 9, 10, 11, 12}; //economy array list
int firstLen = 4; // first class length
int economyLen = 8; //economy class length
int userInput;
int i;

//user prompt
printf("Please type 1 for First Classn");
printf("Please type 2 for Economyn");
printf("Please type 0 to Quitn");
printf("n");
scanf("%d", &userInput); // scanning for user input


if(userInput == 1){
for(i = 0; i < 4; i++){
if(i < firstLen){
printf("Class: First     Seat Number: %dn", firstClass[i]);
}
else{
printf("First Class is Full. Next flight is tomorrow.");
}

}
}

if(userInput == 2){
for (i = 0; i < 8; i++){
if(i < economyLen){
printf("Class: Economy      Seat Number: %dn", economyClass[i]);
}
else{
printf("Economy is Full. Next flight is tomorrow.");
}
}
}
}

因为您想从用户那里获得与userInput != 0一样长的输入,所以您需要在循环中获得用户输入。

userInput将为0时,此循环将中断。

现在,关于从firstClasseconomyClass打印可用座位,您可以维护2变量,通过这些变量可以跟踪上次打印的座位。就像在打印数组值时保持索引一样。

这是一个示例代码。为了更好地理解,我给出了一些内联评论。

int main(int argc, char** argv) {
const int firstClass[] = {1, 2, 3, 4}; //first class array list
const int economyClass[] = {5, 6, 7, 8, 9, 10, 11, 12}; //economy array list
int firstLen = 4; // first class length
int economyLen = 8; //economy class length
int firstClassSeatNumber = 0;
int economyClassSeatNumber = 0;
int userInput;
int i;

while(true) {
//user prompt
printf("Please type 1 for First Classn");
printf("Please type 2 for Economyn");
printf("Please type 0 to Quitn");
printf("n");
scanf("%d", &userInput); // scanning for user input

if (userInput == 0) {
break;  // breaking the loop as we won't take further input from user
}

if(userInput == 1) {
if (firstClassSeatNumber < firstLen) {
// if we've any seat left in first class, then we'll print it
printf("Class: First     Seat Number: %dn", firstClass[firstClassSeatNumber]);
firstClassSeatNumber++; // moving to next seat of first class
}
else {
// don't have any seat left in first class
printf("First Class is Full. Next flight is tomorrow.");
}
}
else if(userInput == 2) {
if (economyClassSeatNumber < economyLen) {
// if we've any seat left in economy class, then we'll print it
printf("Class: Economy      Seat Number: %dn", economyClass[economyClassSeatNumber]);
economyClassSeatNumber++; // moving to next seat of economy class
}
else {
// don't have any seat left in economy class
printf("Economy is Full. Next flight is tomorrow.");
}
}
}
}

最新更新