当前尝试使用气泡排序对数组进行排序,然后获取平均值,但返回的平均值是错误的
Currently trying to sort an array using bubble sort and then getting the average but the average that returns is wrong.
else if (order == "average") {
int average = 0;
int temp;
for (int i = 0; i < NO_TEAMS; i++)
{
for (int j = 0; j < NO_TEAMS - 1; j++)
{
if (ptr[yearIndex].teams[j].fum < ptr[yearIndex].teams[j + 1].fum) {
temp = ptr[yearIndex].teams[i].fum;
ptr[yearIndex].teams[j].fum = ptr[yearIndex].teams[j + 1].fum;
ptr[yearIndex].teams[j + 1].lost = temp;
}
}
}
for (int i = 0; i < NO_TEAMS; i++) {
average = average + ptr[yearIndex].teams[i].fum;
}
对于此代码,平均值返回 26。但是,如果我消除气泡排序代码,则平均值返回 20(这是正确的平均值)。如何解决此问题?
显然,您没有正确交换项目。问题出在以下三行:
temp = ptr[yearIndex].teams[i].fum;
ptr[yearIndex].teams[j].fum = ptr[yearIndex].teams[j + 1].fum;
ptr[yearIndex].teams[j + 1].lost = temp
将第一行更改为索引 j
,而不是i
temp = ptr[yearIndex].teams[j].fum;
相关文章:
- 计算数组c++的平均值
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 计算平均值,不包括上次得分
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- 五个中三个最大参数的平均值,不使用排序算法或向量/数组
- 当前尝试使用气泡排序对数组进行排序,然后获取平均值,但返回的平均值是错误的
- 在C++中对列(数组)中的平均值进行排序和打印