在输入测试的分数和名称之后,输出创建 重复名字,例如我输入埃里克,德里克,约翰,迪克
输出可能会读取erick,derick,derick,derick
我也不确定如何修改此程序以打开txt文件 对数据进行排序?
// main.cpp
// Program 9.4
#include <iostream>
#include<string>
using namespace std;
void sortScore(int *, int, string*);
int main()
{
int numberOfStudents;
cout << "Enter the number of students: " << endl;
cin >> numberOfStudents;
int* score = new int[numberOfStudents];
string* nameOfStudent = new string[numberOfStudents];
for (int i = 0; i<numberOfStudents; i++)
{
cout << "\nEnter Student " << i + 1 << "'s name: " << endl;
cin >> nameOfStudent[i];
cout << "\nEnter his/her score: " << endl;
cin >> score[i];
}
sortScore(score, numberOfStudents, nameOfStudent);
cout << "\nStudent Scores organized from lowest to highest:" << endl;
for (int i = 0; i<numberOfStudents; i++)
{
cout << "\n" << nameOfStudent[i] << "\t\t" << score[i];
}
cout << endl;
delete[] score;
score = 0;
system("pause");
return 0;
}
void sortScore(int *score, int size, string* name)
{
int startScan, minIndex;
int minValue;
string minName;
for (startScan = 0; startScan<(size - 1); startScan++)
{
minIndex = startScan;
minValue = score[startScan];
for (int index = startScan + 1; index<size; index++)
{
if (score[index]<minValue)
{
minValue = score[index];
minIndex = index;
minName = name[index];
}
}
score[minIndex] = score[startScan];
score[startScan] = minValue;
name[minIndex] = name[startScan];
name[startScan] = minName;
}
}
答案 0 :(得分:0)
这里有一个逻辑错误,当没有需要交换时,你实际上是在交换错误信息(丢失minName)。
试试这个:
for (startScan = 0; startScan<(size - 1); startScan++)
{
minIndex = startScan;
minValue = score[startScan];
for (int index = startScan + 1; index<size; index++)
{
if (score[index]<minValue)
{
minValue = score[index];
minIndex = index;
minName = name[index];
}
}
if(minIndex != startScan) {
score[minIndex] = score[startScan];
score[startScan] = minValue;
name[minIndex] = name[startScan];
name[startScan] = minName;
}
}
或者您必须携带minName:
for (startScan = 0; startScan<(size - 1); startScan++)
{
minIndex = startScan;
minValue = score[startScan];
minName = name[startScan];
for (int index = startScan + 1; index<size; index++)
{
if (score[index]<minValue)
{
minValue = score[index];
minIndex = index;
minName = name[index];
}
}
score[minIndex] = score[startScan];
score[startScan] = minValue;
name[minIndex] = name[startScan];
name[startScan] = minName;
}