#include<cstdlib>
#include<iostream>
#include<cctype>
using namespace std;
int seats[10][10];
char row;
int colume;
int num=0;
void seatf ();
void showSeats();
int isContinue();
int main(void){
do{
system("cls");
seatf();
showSeats();
}while(isContinue());
system("pause");
return EXIT_SUCCESS;
}
void seatf(){
while(1){
cout << "請選座位表"<<endl<<endl;
cout << "請輸入第幾排";
cin >> row;
row = toupper(row);//變數=toupper(變數);寫法固定
if(row<65 || row>90){
cout << "請輸入正確排數"<<endl;
system("pause");
system("cls");
continue;
}
cout << "請輸入第幾欄";
cin >> colume;
if(colume<1 || colume>10 ){
cout << "請輸入正確欄數" <<endl;
system("pause");
system("cls");
continue;
}
cout <<"您輸入的座位是:" << row << colume << endl;
if(seats[row-'A'][colume-1]==1){
cout << "座位已經被選走了"<<endl;
continue;
}else{
seats[row-'A'][colume-1]=1;
break;
}
}
}
void showSeats(){
cout << "\n 查看座位表"<<endl<<endl;
cout << " ";
for(colume=1;colume<=10;colume++){
cout << colume << " ";
}
cout << endl;
for(row='A';row<='J';row++){
cout << row;
for(colume=1;colume<=10;colume++){
if(seats[row-'A'][colume-1]==1){
cout << " x";
num++;
}else{
cout << " o";
}
}
cout << endl;
}
}
int isContinue(){
char select;
cout << "\n請輸入是否要繼續(Y or N):";
cin >> select;
select = toupper(select);
if(select<89 && select>78){
cout << "請輸入Y or N"<<endl;
return 0;
}else if(select ==89){
cout << "請選座位"<<endl;
return 1;
}else if(select<78 || select>89){
cout << "請輸入Y or N"<<endl;
return 0;
}else{
cout << "不繼續輸入"<<endl;
cout << "共選"<<num <<"個座位"<<endl;
return 0;
}
}
因为你的num是全局变量。 6 = 1 + 2 + 3
不要用全局变量
最简单改法是
把 num++ 从 showSeats函数 移到 seat函数里 seats[row-'A'][colume-1]=1; 这句话的后面。
【以下回答由 GPT 生成】
问题出现的原因是因为变量num
没有在每次选择座位前重新初始化为0,导致每次计算座位数量时都是在原来的基础上累加,而没有重新计数。
解决这个问题比较简单,只需要在selectSeat
函数的开头,在用户选择座位之前,添加一行代码num = 0;
将num
初始化为0,以重新计数被选座位的数量。
修改后的代码如下所示:
void selectSeat(){
num = 0; // 添加代码,将num初始化为0
while(1){
// 程序其他部分保持不变
}
}
修改后的代码可以解决计算座位数量不正确的问题。
【相关推荐】