gpt4 book ai didi

c++ - 目前正在尝试使用冒泡排序对数组进行排序,然后获取平均值,但返回的平均值是错误的。

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:58:01 25 4
gpt4 key购买 nike

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++ - 目前正在尝试使用冒泡排序对数组进行排序,然后获取平均值,但返回的平均值是错误的。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35307604/

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