gpt4 book ai didi

c++ - 颠倒排序顺序

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

你好,我有一个与大学类(class)表有关的程序,它有几个排序函数,我们将处理升序 gpa 函数和降序 gpa 函数。

这是降序函数,它可以正常运行:

void classSchedule::downGPA(classSchedule schedule[], int& numElems)
{
classSchedule temp;
int end;
for (end = numElems - 1; end >= 0; end--)
{
for (int counter = 0; counter < end; counter++)
{
if (schedule[counter].classNumber == 000)
counter++;
if (schedule[counter].currentGPA < schedule[counter + 1].currentGPA)
{

temp = schedule[counter];
schedule[counter] = schedule[counter + 1];
schedule[counter + 1] = temp;
}
}
}
schedule->outputToConsole(schedule, numElems);

}

这是升序函数,由于某种原因它什么都不显示:

void classSchedule::upGPA(classSchedule schedule[], int& numElems)
{
classSchedule temp;
int end;
for (end = numElems - 1; end >= 0; end--)
{
for (int counter = 0; counter < end; counter++)
{
if (schedule[counter].classNumber == 000)
counter++;
if (schedule[counter].currentGPA > schedule[counter + 1].currentGPA)
{

temp = schedule[counter];
schedule[counter] = schedule[counter + 1];
schedule[counter + 1] = temp;
}
}
}
schedule->outputToConsole(schedule, numElems);
}

我更改了标志,但它没有显示任何内容,有人知道为什么吗?

编辑:

按要求输出函数

void classSchedule::outputToConsole(classSchedule currentSchedule[], int numElems)
{
int i;
cout << endl << "Dept" << "\t" << "Class Number\t" "Credit Hours" << "\t" << "Name"
<< "\t" << "Room Number" << "\tGPA"
<< endl << "----" << "\t------------" << "\t------------- ----"
<< "\t-----------" << "\t---";
for (i = 0; i < numElems; i++)
{
if (currentSchedule[i].displayOrNot == "FALSE")
i++;
if(currentSchedule[i].currentGPA == -1)
{
break;
}
cout << endl << currentSchedule[i].classDepartment << " " << currentSchedule[i].classNumber << " \t"
<< " " << currentSchedule[i].creditHours << " \t"
<< currentSchedule[i].teacherLastName << " " << currentSchedule[i].teacherFirstName
<< "\t" << currentSchedule[i].roomWingAndNumber << "\t" << currentSchedule[i].currentGPA;
}

}

最佳答案

您的排序函数有几个问题:

  • 你的循环条件是counter < end并且你使用 [counter+1] 作为数组索引,你将在第一次迭代时超出数组边界,建议将条件更改为 counter < end -1
  • 代码 if (schedule[counter].classNumber == 000)是危险的,并且不清楚你为什么需要它。可能是为了避免之前的错误

Coolprit 好像是这段代码:

if(currentSchedule[i].currentGPA == -1)
{
break;
}

当您按降序排序时,记录会排到末尾并且工作正常。但是,当您按升序排序时,该记录处于开始状态并且您中断了循环。如果您想跳过 GPA -1 的记录,请替换 breakcontinue在该代码中。

关于c++ - 颠倒排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28352007/

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