[英]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.