【发布时间】:2017-11-09 01:21:49
【问题描述】:
尝试从文本文件创建唯一成绩列表。输出有问题,消除重复。目前,我正在尝试将每个前一个数组条目的值与下一个数组条目的值进行比较,如果它们不同,则将结果输出到 outfile,但只是输出一个空文件。
我也很好奇是否有一个简单的解决方法可以将排序从“低到高”更改为“高到低”。先感谢您。
#include <iostream>
#include <string>
#include <limits>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
int testScoreArray[100];
void selectSort(int testScoreArray[], int n);
void fileOutput(int testScoreArray[]);
int main()
{
int n = 100;
ifstream infile;
infile.open("testscoresarrayhomework.txt");
for (int i = 0; i < 100; i++) {
infile >> testScoreArray[i];
}
selectSort(testScoreArray, n);
fileOutput(testScoreArray);
infile.close();
return 0;
}
void selectSort(int testScoreArray[], int n)
{
//pos_min is short for position of min
int pos_min, temp;
for (int i = 0; i < n - 1; i++) {
pos_min = i; //set pos_min to the current index of array
for (int j = i + 1; j < n; j++) {
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i) {
temp = testScoreArray[i];
testScoreArray[i] = testScoreArray[pos_min];
testScoreArray[pos_min] = temp;
}
}
};
void fileOutput(int testScoreArray[])
{
ofstream outfile;
int gradeEvent = 0;
int previousGrade = 0;
outfile.open("testscoresoutput.txt");
outfile << "Test Score Breakdown: ";
outfile << endl
<< "Score / Occurance";
for (int i = 0; i < 100; i++) {
previousGrade = i;
if (previousGrade && previousGrade != i) {
outfile << '\n' << testScoreArray[i] << " / " << gradeEvent;
}
}
outfile.close();
};
【问题讨论】:
-
“[I]sn't working normal”是一个非常糟糕的问题描述。请read about how to ask good questions。我也推荐你learn how to debug your programs。最后,除非您的任务是排序,否则请改用
std::sort。和std::unique排序后删除重复项。 -
...并可能用向量替换 C 样式的数组。
-
您需要schedule an emergency appointment with your rubber duck 才能逐行审查
fileOutput()中的逻辑,这些逻辑完全完全被破坏了。之后,按照你的橡皮鸭的指示,一切都会很快解决。