簡體   English   中英

匹配用戶輸入並通過數字c ++計算輸入

[英]Matching user inputs and calculating the inputs by the number c++

我的問題是記錄用戶5個輸入並將它們匹配到正確的代碼。 singleperson代碼為1, couple代碼為2, family代碼為3。因此,用戶輸入的只是這3個數字。最后,我必須按類別計算總人數。 我運行了代碼,並遇到運行時錯誤,說變量“組”周圍的堆棧已損壞,夫婦和家庭均為0時,總是只有5個單打。對不起,我剛剛上學,我有點模糊。

int singleperson=0;
int couple=0;
int family3=0;

int groups[]={0,0,0,0,0};
cout << "Enter group #1:";
cin >>groups[0];
cout << "Enter group #2:";
cin >>groups[1];
cout << "Enter group #3:";
cin >>groups[2];
cout << "Enter group #4:";
cin >>groups[3];
cout << "Enter group #5:";
cin >>groups[4];
for (int a=0; a<=4;a++)
{
    if(groups[a]=1)
    {
        singleperson= singleperson + 1;
    }
    else if(groups[a]=2)
    {
        couple = couple +1;
    }
    else
    {
        family3= family3+1;
    }
}
cout<<"Statistics"<<endl;
cout <<singleperson<<"Singles"<<endl;
cout<<couple<<"Couples"<<endl;
cout<<family3<<"Families"<<endl;

因為group大小為4並且您嘗試插入5th位。 正如@ antonio-garrido指出的,檢查相等性,我們使用==並且=用於賦值。

int groups[]={0,0,0,0,0};


for (int a=0 ; a <= 4; a++) {
    if(groups[a] == 1) {
        singleperson= singleperson + 1;
    } else if(groups[a] == 2) {
        couple = couple +1;
    } else {
        family3= family3+1;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM