1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Data
{
string Name;
double Grade;
};
void getData(Data *, int);
void selectionSort(Data *, int);
double getAverage(Data *, int);
void displayData(Data *, int, double);
int main()
{
Data *Test;
double Average; //average of the scores
int Scores; //number of scores
//Get number of scores
cout << "How many scores do you have to average? ";
cin >> Scores;
// to hold the user-defined number of scores
Test = new Data[Scores];
getData(Test, Scores);
selectionSort(Test, Scores);
getAverage(Test, Scores);
displayData(Test, Scores, Average);
delete [] Test;
Test = 0;
return 0;
}
void getData(Data *Test, int Scores)
{
cout << "Enter the names and scores for each student.\n";
for(int i = 0; i < Scores; i++)
{
cout << "Student #" << (i + 1) << endl;
cout << " Name: ";
cin.ignore();
getline(cin, (Test + i)->Name);
do
{
cout << " Score :";
cin >> (Test + i)->Grade;
if ((Test + i)->Grade < 0)
{
cout << "Scores must be greater than 0.\n"
<< "Re-enter ";
}
cout << endl;
} while ((Test + i)->Grade < 0);
}
}
void selectionSort(Data *Test, int Scores)
{
int startscan, minIndex;
Data *minValue;
for (startscan = 0; startscan < (Scores - 1); startscan++)
{
minIndex = startscan;
*minValue = Test[startscan];
for (int i = startscan + 1; i < Scores; i++)
{
if ((Test + i)->Grade < minValue->Grade)
{
*minValue = Test[i];
minIndex = i;
}
}
Test[minIndex] = Test[startscan];
Test[startscan] = * minValue;
}
}
double getAverage(Data *Test, int Scores)
{
double Total;
double average;
for (int i = 0; i < Scores; i++)
{
Total += (Test + i)->Grade;
}
average = Total / Scores;
return average;
}
void displayData(Data *Test, int Scores, double Avg)
{
cout << " Test scores\n";
cout << "Number of scores: " << Scores << endl;
cout << "Scores in ascending-order:\n";
for (int i = 0; i < Scores; i++)
{
cout << (Test + i)->Name << ": " << (Test + i)->Grade << endl;
}
cout << fixed << showpoint << setprecision(2);
cout << "Average of scores: " << Avg << endl;
}
|