简体   繁体   中英

why i cant return 2 value in a user defined function and display it in the main functionn? can someone help me

this countGender function need to receive what gender and return 2 value which is female or male

    int countGender(string gender)
    {
        int numGender[2] = {0};
        
        if(gender == "F")
        numGender[1]++;
        else if(gender == "M")
        numGender[2]++;
        
        return numGender[2];
    }

You're mismatching effect of function and object you want to store results. THe countGender<\/code> function looks like a mess resulting of shotgun debugging.

More of, to actually perform counting, you have to pass existing value on each iteration. One of logical things to do is to pass the array by reference<\/a> . Also, array in C++ have zero-based indexes.

void countGender(int (&numGender)[2], string gender)
{    
    if(gender == "F") 
        numGender[0]++; 
    else if(gender == "M") 
        numGender[1]++; 
}

int main()
{
    string gender;
    int numGender[2] = {};
    int n;
    
    cout<<"Enter number of respondents:";
    cin>>n;
    
    for(int i=0; i<n; i++)
    {
        cout<<"\nEnter Gender (F-Female, M-Male):";
        cin>>gender;
        countGender(numGender,gender);
    }
    cout<<"\nFemale - "<<numGender[0];
    cout<<"\nMale - "<<numGender[1];
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM