gpt4 book ai didi

c++ - 从函数发出返回值

转载 作者:行者123 更新时间:2023-11-28 06:01:28 25 4
gpt4 key购买 nike

我的程序计算每个学生的平均分。它输出平均数和字母等级。有了这两个函数,我可以很好地获得每个学生的字母成绩,但我不知道如何获得每个字母成绩的总数。 (请注意,我不允许在此作业中使用结构、数组或 vector 等 :( )

#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() 中返回每个字母等级的总数?谢谢!

最佳答案

我不知道你可以做什么或不可以做什么。
考虑到您不能使用数组或结构,您只能通过将计数器作为参数传递给 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...]);
}

关于c++ - 从函数发出返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33204781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com