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
|
#include <iostream>
#include <iomanip>
using namespace std;
/*This program allows the user to input some number of grades,
up to a max of 100. The program will then use functions to determine
the mean and median of the grades. Finally the program will output
the sorted grades from least to greatest. Inputs are the number of
grades, and the grades themselves. Outputs are the mean, median,
and the grades in sorted form.*/
int main ()
{
const int size = 100;
float grades[size] = {0};
int userSize;
float avg = 0.0;
float mid = 0.0;
float mean (float grades[], int userSize, float avg);
float median (float grades[], int userSize, float mid);
cout << "Enter number of grades to be entered: ";
cin >> userSize;
if (userSize > 100)
{
cout << "Too many grades" << endl;
return 0;
}
for (int i = 0; i < userSize; i++)
{
cout << "Please enter grade: " << endl;
cin >> grades[i];
if (cin.fail() || grades[i] < 0 || grades[i] > 100)
{
cout << "Please enter a valid grade within";
cout << "the range of 0 - 100" << endl;
cin.clear();
i--;
continue;
}
avg = mean (grades,userSize, avg);
}
mid = median (grades, userSize, mid);
int i, j;
for (i = 0, j = 0; i < userSize; i++, j++)
{
cout << grades[i] << " ";
if (j == 4)
{
j = 0;
cout << "\n";
}
}
cout << endl;
cout << "The mean of the grades entered is: " << fixed << setprecision(2) << avg << endl;
cout << "The median of the grades entered is: " << fixed << setprecision(2) << mid << endl;
cin.ignore(2);
return 0;
}
/*The 'mean' function is to find the middle or mean of the grades array.
The inputs to this function are all of the array values, the size
of the array, and the output is the mean of the array 'grades'*/
float mean (float grades[ ], int userSize, float avg = 0.00)
{
float sum = 0.0;
for (int j = 0; j < userSize; j++)
{
sum += grades[j];
}
return (sum / userSize);
}
/*The 'median' function is sort the array from least to greatest,
then find the median of the grades. The inputs are the array values,
the size of the array, and the output is the median value*/
float median (float grades[ ], int userSize, float mid = 0.0)
{
for (int outer = 0; outer < userSize; outer++)
{
for (int inner = 0; inner < userSize - 1; inner++)
{
if (grades[inner] > grades[inner + 1])
{
float temp;
temp = grades[inner];
grades[inner] = grades[inner + 1];
grades[inner + 1] = temp;
}
}
}
if (userSize % 2 == 0)
{
mid = ((grades[userSize/2] + (grades[(userSize/2)-1])) /2);
}
else
{
mid = grades[userSize / 2];
}
return mid;
}
|