从函数发出返回值

时间:2015-10-19 00:18:57

标签: c++ function

我的课程计算每个学生的平均分数。它输出数字平均值和字母等级。有了这两个功能,我能够很好地得到每个学生的字母等级,但是我无法弄清楚如何获得每个字母等级的总数。 (请注意,我不允许在此作业中使用结构,数组或向量等:()

#include <iostream>

string letterScore(double&);
int scoreCounter(string&);

using namespace std;

int main() {
    /* repeat for 5 students */
    for (int i = 0; i < 5; i++) {

        /* for simplicity, assume avgScore has already been calculated 
           and that function returned the average scores received for 
           each student: 90, 80, 70, 60, and 50 respectively */

        // pass the average score to figure out letter grades
        string letterscore = letterScore(avgScore);
    }

    return 0;
}

string letterScore(double& avgScore) {

    int As, Bs, Cs, Ds, Fs = 0;
    string letterscore;

    if (avgScore >= 90)
    {
        letterscore = "A";
        As = scoreCounter(letterscore);
    }
    else if (avgScore >= 80 && avgScore <= 89)
    {
        letterscore = "B";
        Bs = scoreCounter(letterscore);
    }
    else if (avgScore >= 70 && avgScore <= 79)
    {
        letterscore = "C";
        Cs = scoreCounter(letterscore);
    }
    else if (avgScore >= 60 && avgScore <= 69)
    {
        letterscore = "D";
        Ds = scoreCounter(letterscore);
    }
    else if (avgScore >= 50 && avgScore <= 59)
    {
        letterscore = "F";
        Fs = scoreCounter(letterscore);
    }

    return letterscore;
}

int scoreCounter(string& letterscore) {
    int counter = 0;

    if (letterscore == "A")
    {
        counter++;
    }
    else if (letterscore == "B")
    {
        counter++;
    }
    else if (letterscore == "C")
    {
        counter++;
    }
    else if (letterscore == "D")
    {
        counter++;
    }
    else if (letterscore == "F")
    {
        counter++;
    }

    return counter;
}

我知道问题在于第二个功能以及我如何连接这两个功能。现在,As,Bs,Cs,Ds,Fs的输出为0而不是1(假设上面提到的90,80,70,60和50的平均值)。我怎样才能回到main()每个字母等级的总数?谢谢!

1 个答案:

答案 0 :(得分:1)

我不确切地知道你可以做什么或不做什么 考虑到您不能使用数组或结构,只需使用letterScore函数解决问题,方法是将参数作为参考传递:

string letterScore(double& avgScore, int& countA, int& countB, int& countC, [etc...]) {
    string letterscore;

    if (avgScore >= 90)
    {
        letterscore = "A";
        countA++; // here is the counter !
    }
    [etc...] // do the same for other blocks

和您的main()

int countA = countB = [etc...] = 0;
for (int i = 0; i < 5; i++) {
        string letterscore = letterScore(avgScore, countA, countB, [etc...]);
    }