简体   繁体   English

"<i>why i cant return 2 value in a user defined function and display it in the main functionn?<\/i>为什么我不能在用户定义的函数中返回 2 个值并将其显示在主函数中?<\/b> <i>can someone help me<\/i>有人能帮我吗<\/b>"

[英]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此 countGender 函数需要接收什么性别并返回 2 个值,即女性或男性

    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. countGender<\/code>函数看起来像是霰弹枪调试的结果。

You can't return an array in a function.您不能在函数中返回数组。 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> .要做的一件合乎逻辑的事情是通过引用<\/a>传递数组。 Also, array in C++ have zero-based indexes.此外,C++ 中的数组具有从零开始的索引。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 看到&#39;-&#39;字符时我无法结束getline,有人可以帮助我getline()ifstream in c ++ - I cant end getline when see ' - ' character, can someone help me getline() ifstream in c++ 有人可以帮我这个功能的指针版本 - Can someone help me with the pointer version of this function 有人可以帮我修改此代码。 我正在尝试显示棋盘格C ++ QT - can someone help me modify this code. I'm trying to Display a checkerboard C++ QT 我正在尝试参考快速排序实现双 pivot 分区 function。 有人能帮我吗? - i am trying to implement the double pivot partition function in reference to quicksort. Can someone help me? 有人可以帮我吗? [等候接听] - Can someone help me this? [on hold] 有人可以帮助我使用 C++ 中的递归函数吗? - Can someone help me with Recursive Function in c++? 有人可以帮我上这门课吗? - Can someone help me with this class? 有人可以帮我理解为什么我在这里遇到错误我相信这是因为约会单链表 - Can someone help me understand why im getting an error here I believe its because of the appointment singly linked list 为什么我不能将数组值返回到main函数? - why can't i return array values to main function? 为什么我不能从主函数返回更大的值? - Why can't I return bigger values from main function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM