循环次数比我预期的要多
Looping more times than I expect
本文关键字:循环 更新时间:2023-10-16
>我有以下函数,它采用学生(具有姓名和注册号)的向量,然后计算这些学生的最小,最大和平均分数(他们的分数存储在地图中),输出部分正确,它应该只打印每个学生一次,但是我编写的代码打印出每个学生的次数与存储在其向量中的标记数量相同。我花了一些时间试图解决这个问题,我相信问题是我的第三个 for 循环,有人可以解释为什么它像这样循环以及如何解决它。谢谢。
string func1(vector<Student>students, float mark) {
int count = 0;
float avg, min, max = 0;
list<string> toPrint;
map<string, float> temp;
vector<float> v;
//for every student
for(size_t a=0; a < students.size(); ++a) {
temp = students[a].getCopyOfMap();
v.erase(v.begin(), v.end());
avg = 0;
min = 0;
max = 0;
count = 0;
for(map<string, float>::iterator it = temp.begin(); it != temp.end(); ++it) {
stringstream ss;
ss << it->second;
v.push_back(stof(ss.str()));
}
for(map<string, float>::iterator it = temp.begin(); it != temp.end(); ++it) {
max = *max_element(v.begin(), v.end());
min = *min_element(v.begin(), v.end());
for (size_t b=0; b < v.size(); ++b) {
avg = avg + v[b];
count++;
}
avg = avg/count;
if(avg > mark) {
stringstream out;
out << students[a].getRegNo() << " " << min << " " << max << " " << avg << endl;
toPrint.push_back(out.str());
}
}
}
你的"if"语句应该在你的第三个"for"之外,但仍在第一个"for"之内。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 在循环C++中指定字符串之后,不会打印该字符串