用户输入的成绩数。我正在使用动态数组分配。我对我的代码很有信心,但Xcode在我的排序函数中给了我一个错误。我认为我做得对,但显然有些不对劲,我不确定在哪里。我仍然试图找出动态内存分配,所以我确定这是我的错误产生的地方,我只是不知道原因在哪里。这是我的完整计划:
// This program demonstrates the use of dynamic arrays
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
//Function Prototypes
void sort(float *score[], int numOfScores);
int main()
{
float *scores;
int total = 0;
float average;
float numOfScores;
int count;
cout << fixed << showpoint << setprecision(2);
cout << "Enter the number of scores to be averaged and sorted.";
cin >> numOfScores;
scores = new float(numOfScores);
for ( count = 0; count < numOfScores; count++)
{
cout << "Please enter a score:" << endl;
cin >> scores[count]; }
for (count = 0; count < numOfScores; count++)
{
total = total + scores[count];
}
average = total / numOfScores;
cout << "The average score is " << average << endl;
sort(*scores, numOfScores);
delete [] scores;
return 0;
}
//*******************************************
// Sort Function
// Bubble sort is used to sort the scores
//*******************************************
void sort(float *score[], int numOfScores)
{
do
{
bool swap = false;
for (int count = 0; count < (numOfScores -1); count++)
{
if (*score[count] > *score[count+1])
{
float *temp = score[count];
score[count] = score[count+1];
score[count+1] = temp;
swap = true;
}
}
}while(swap); //This is where I'm receiving the error.
}
谢谢!
答案 0 :(得分:0)
swap
是do...while
循环的本地,因此不能在while条件中使用它。有人会发现与此相关的错误,但由于您已using namespace std;
和#include <algorithm>
,因此您已将std::swap
函数引入程序范围
while(swap);
尝试将std::swap
转换为函数指针,但它不能重载,并且不知道要使用哪个重载。
有关避免使用using namespace std;
的原因的进一步阅读,请参阅:Why is “using namespace std” in C++ considered bad practice?