Showing Below Average Scores in Player Scoring Program - c++

I'm trying to create a program in which the user can enter up to 100 player names and scores, and then have it print out all the players' names and scores, followed by an average of the scores, and finally, display players whose scores were below average. I've managed to do all of that except for the final piece, displaying below average scores. I'm kind of unsure about how to go about it. In my DesplayBelowAverage function, I've attempted to have it read the current player's score and compare it to the average to see if it should be printed out as a below average score, but it doesn't seem to recognize the averageScore value I created in the CalculateAverageScores function. Here's my code:
#include <iostream>
#include <string>
using namespace std;
int InputData(string [], int [], int);
int CalculateAverageScores(int [], int);
void DisplayPlayerData(string [], int [], int);
void DisplayBelowAverage(string [], int [], int);
void main()
{
string playerNames[100];
int scores[100];
int sizeOfArray = sizeof(scores);
int sizeOfEachElement = sizeof(scores[0]);
int numberOfElements = sizeOfArray / sizeOfEachElement;
cout << numberOfElements << endl;
int numberEntered = InputData(playerNames, scores, numberOfElements);
DisplayPlayerData(playerNames, scores, numberEntered);
CalculateAverageScores(scores, numberEntered);
cin.ignore();
cin.get();
}
int InputData(string playerNames[], int scores[], int size)
{
int index;
for (index = 0; index < size; index++)
{
cout << "Enter Player Name (Q to quit): ";
getline(cin, playerNames[index]);
if (playerNames[index] == "Q")
{
break;
}
cout << "Enter score for " << playerNames[index] << ": ";
cin >> scores[index];
cin.ignore();
}
return index;
}
void DisplayPlayerData(string playerNames[], int scores[], int size)
{
int index;
cout << "Name Score" << endl;
for (index = 0; index < size; index++)
{
cout << playerNames[index] << " " << scores[index] << endl;
}
}
int CalculateAverageScores(int scores[], int size)
{
int index;
int totalScore = 0;
int averageScore = 0;
for (index = 0; index < size; index++)
{
totalScore = (totalScore + scores[index]);
}
averageScore = totalScore / size;
cout << "Average Score: " << averageScore;
return index;
}
void DisplayBelowAverage(string playerNames[], int scores[], int size)
{
int index;
cout << "Players who scored below average" << endl;
cout << "Name Score" << endl;
for (index = 0; index < size; index++)
{
if(scores[index] < averageScore)
{
cout << playerNames[index] << " " << scores[index] << endl;
}
}
}

You are calculating the averageScore variable in the CalculateAverageScore and it is local to that function only so DisplayBelowAverage has no idea about the averageScore value. That's why your logic is not working.
In order to solve this there are two options:
Declare the averageScore as global (although it is not advisable to have global variables)
Pass the averageScore to the DisplayBelowAverage as a parameter. This is a better approach. So what you should do is return the average score that you calculate in CalculateAverageScore and store it in some variable and then pass that to DisplayBelowAverage function as a parameter.
Hope this helps

Related

Creating program that takes 5 grades from the user and finds the lowest grade, and then outputs average grade after dropping the lowest grade entered

`
#include <iostream>
#include <iomanip>
using namespace std;
void getGrades(double g[], const int SIZE)
{
cout << "Please enter " << SIZE << " grades:" << endl;
for(int i = 0; i < SIZE; i++)
{
cin >> g[i];
}
}
double getAverage(double g[], const int SIZE)
{
int total = 0;
for(int i = 0; i < SIZE; i++)
{
total += g[i];
}
return total/SIZE;
}
void findDropInfo(double g[], const int SIZE, int &lowest, double average)
{
int total = 0;
lowest = g[0];
for(int i = 1; i < SIZE; i++)
{
if (lowest > g[i]) {
lowest = g[i];
}
}
average = (total - lowest)/SIZE;
return average;
}
void printData(double g[], int lowest, double average, double avg_before)
{
cout << "The 5 grades entered by the user are:" << endl;
cout << g[];
cout << "Grade dropped: " << lowest << endl;
cout << "Final Average: " << average << endl;
cout << "Average before drop: " << avg_before << endl;
}
// TODO: Complete the function definitions
int main()
{
const int SIZE = 5;
double grades[SIZE];
int lowest;
double avg,
avgBeforeDrop;
// TODO: Add function calls
getGrades(grades[SIZE], SIZE);
getAverage(grades[SIZE], SIZE);
findDropInfo(grades[SIZE], SIZE, lowest, avg);
printData(grades[SIZE], lowest, avg, avgBeforeDrop);
return 0;
}
`
Whenever I run the program, I get multiple errors saying there's no matching candidate function. I'm not sure if the problems are in the functions themselves or in the function calls, but from what I know the functions themselves should be fine. I'm also told there's an expected expression in g[] but I' not sure what's wrong there either, as it's meant to be empty.
Most issues have already been resolved in the comments, but note: cout << g[] does not print the elements of g.
The way to do this is
char separator = /* the character you want to use to separate the printed elements of g */
for (int i = 0; i < SIZE; i++)
{
cout << g[i] << separator;
}
if (separator != '\n') cout << '\n'; //this is to put the next print on the next line
I would put this as a comment but I don't have enough reputation :|

How do I convert from arrays to STL vectors?

In my class we recently got introduced to STL vectors. My professor has given us a program that uses arrays, and we are to convert it to use std::vectors instead. He would like us to use iterators, so we're not allowed to use square brackets, the push_back member function, or the at member function. Here's one of the for loops from the program I have to convert:
void readData(Highscore highScores[], int size)
{
for(int index = 0; index < size; index++)
{
cout << "Enter the name for score #" << (index + 1) << ": ";
cin.getline(highScores[index].name, MAX_NAME_SIZE, '\n');
cout << "Enter the score for score #" << (index + 1) << ": ";
cin >> highScores[index].score;
cin.ignore();
}
cout << endl;
}
`
I'm just not quite understanding how to convert them. so far, I was kind of able to get this: for (vector <Highscore> :: iterator num = scores.begin(); num < scores.end(); num++)for the for loop. It doesn't quite make sense to me so I was hoping I can get some more tips or even more information on how to convert them. I don't want an answer, simply just a tip. Thank you! (if its of any help, this is the program I am having to convert and these are the four headers we have to use
void getVectorSize(int& size);
void readData(vector<Highscore>& scores);
void sortData(vector<Highscore>& scores);
vector<Highscore>::iterator findLocationOfLargest(
const vector<Highscore>::iterator startingLocation,
const vector<Highscore>::iterator endingLocation);
void displayData(const vector<Highscore>& scores);
above are the headers that have to be used (having to use these instead of the programs headers)
#include <iostream>
using namespace std;
const int MAX_NAME_SIZE = 24;
struct Highscore{
char name[MAX_NAME_SIZE];
int score;
};
void getArraySize(int& size);
void readData(Highscore highScores[], int size);
void sortData(Highscore highScores[], int size);
int findIndexOfLargest(const Highscore highScores[], int startingIndex, int size);
void displayData(const Highscore highScores[], int size);
int main()
{
Highscore* highScores;
int size;
getArraySize(size);
highScores = new Highscore[size];
readData(highScores, size);
sortData(highScores, size);
displayData(highScores, size);
delete [] highScores;
}
void getArraySize(int& size){
cout << "How many scores will you enter?: ";
cin >> size;
cin.ignore();
}
void readData(Highscore highScores[], int size)
{
for(int index = 0; index < size; index++)
{
cout << "Enter the name for score #" << (index + 1) << ": ";
cin.getline(highScores[index].name, MAX_NAME_SIZE, '\n');
cout << "Enter the score for score #" << (index + 1) << ": ";
cin >> highScores[index].score;
cin.ignore();
}
cout << endl;
}
void sortData(Highscore highScores[], int numItems) {
for (int count = 0; count < numItems - 1; count++){
swap(highScores[findIndexOfLargest(highScores, count, numItems)],
highScores[count]);
}
}
int findIndexOfLargest(const Highscore highScores[], int startingIndex, int numItems){
int indexOfLargest = startingIndex;
for (int count = startingIndex + 1; count < numItems; count++){
if (highScores[count].score > highScores[indexOfLargest].score){
indexOfLargest = count;
}
}
return indexOfLargest;
}
void displayData(const Highscore highScores[], int size)
{
cout << "Top Scorers: " << endl;
for(int index = 0; index < size; index++)
{
cout << highScores[index].name << ": " << highScores[index].score << endl;
}
}
You maybe looking for one of two things.
If you want to add something to a vector, the function is push_back
vecScores.push_back(value) ; //in a for loop.
https://www.cplusplus.com/reference/vector/vector/push_back/
If you want to add something to a map, you could just use the form of
mapScore[index]=value ; // in a for loop.
https://www.cplusplus.com/reference/map/map/operator[]/
Probably your professor wants you to write something like this:
void readData(std::vector<Highscore>& highScores)
{
for (auto it = highScores.begin(); it != highScores.end(); ++it) {
cout << "Enter the name for score #" << std::distance(highScores.begin(), it) << ": ";
cin.getline(it->name, MAX_NAME_SIZE, '\n');
cout << "Enter the score for score #" << std::distance(highScores.begin(), it) << ": ";
cin >> it->score;
cin.ignore();
}
cout << endl;
}
where it is the iterator that's incremented via ++it from highScores.begin() to just before highScores.end(); then you access the members of the highScores's element "pointed by" it via it->member.
Here's a complete demo.
By the way, considering how much your professor likes void(some_type&) functions (and using namespace std;, if that was not your own idea), I would doubt you have much to learn from him. You better buy a good book.
I would do it like this, also get used to typing std::
Why is "using namespace std;" considered bad practice?
Also be careful with signed/unsigned, be precise about it.
If something can't have a negative value use unsigned types (or size_t)
#include <iostream>
#include <string>
#include <vector>
struct HighScore
{
std::string name;
unsigned int score;
};
// use size_t for sizes (value will always >0)
std::vector<HighScore> GetHighScores(size_t size)
{
std::vector<HighScore> highScores;
std::string points;
for (size_t index = 0; index < size; index++)
{
HighScore score;
std::cout << "Enter the name for score #" << (index + 1) << ": ";
std::cin >> score.name;
std::cout << "Enter the score for score #" << (index + 1) << ": ";
std::cin >> points;
// convert string to int
score.score = static_cast<unsigned int>(std::atoi(points.c_str()));
highScores.push_back(score);
}
std::cout << std::endl;
return highScores;
}
int main()
{
auto highScores = GetHighScores(3);
return 1;
}

C++ Average Calculation Function Returning 0 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm writing a program that calculates the batting averages of a user defined number of players. The program displays the name of a player, their number of times at bat, number of hits, and their batting average. Finally, it displays the total number of times the players were at bat, the total number of hits, and the overall average. For some reason, the functions that calculate the individual player average and overall average are returning 0. It's probably something small, but I'm stumped as to how to try and fix it.
//Batting Average Calculator
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//Create Structure
struct Record
{
string name;
int AB;
int hit;
double avg;
};
int getSize(int);
void getData(Record[], int );
int calculateTotalAB(Record[], int, int);
int calculateTotalHit(Record[], int, int);
double calculateTotalAvg(Record[], int, double);
void calculateAvg(Record[], int);
void display(Record[], int, int , int, double);
int main()
{
const int MaxSize = 50;
Record players[MaxSize];
int size = 0;
int totalAB = 0;
int totalHit = 0;
double totalAvg = 0;
size = getSize(size);
getData(players, size);
totalAB = calculateTotalAB(players, size, totalAB);
totalHit = calculateTotalHit(players, size, totalHit);
calculateAvg(players,size);
totalAvg = calculateTotalAvg(players, size, totalAvg);
display(players, size, totalHit, totalAB, totalAvg);
}
//get number of players to be calculated
int getSize(int size)
{
cout << "Please enter the number of players on the team: ";
cin >> size;
return size;
}
//get Player name, AB, and hit
void getData(Record players[], int size)
{
string dummy;
getline(cin, dummy);
for (int i = 0; i < size; i++)
{
cout << "Please input the name of student " << i + 1 << ": ";
getline(cin, players[i].name);
cout << "Please input the number of times "<< players[i].name << " was at bat: ";
cin >> players[i].AB;
cout << "Please input the number of hits for " << players[i].name << ": ";
cin >> players[i].hit;
cout << " " << endl;
getline(cin, dummy);
}
}
int calculateTotalAB(Record players[], int size, int totalAB)
{
for (int i = 0; i < size; i++)
{
totalAB = totalAB + players[i].AB;
}
return totalAB;
}
int calculateTotalHit(Record players[], int size, int totalHit)
{
for (int i = 0; i < size; i++)
{
totalHit = totalHit + players[i].hit;
}
return totalHit;
}
void calculateAvg(Record players[], int size)
{
for (int i = 0; i < size; i++)
{
players[i].avg = players[i].hit / players[i].AB;
}
}
double calculateTotalAvg(Record players[], int size, double totalAvg)
{
double j = 0;
for (int i = 0; i < size; i++)
{
j = j + players[i].avg;
}
totalAvg = j / size;
return totalAvg;
}
void display(Record players[], int size, int totalHit, int totalAB, double totalAvg)
{
cout << fixed << showpoint << setprecision(3);
cout << "Player AB Hit Avg" << endl;
cout << " " << endl;
for (int i = 0; i < size; i++)
{
cout << players[i].name << setw(8) << players[i].AB << setw(5) << players[i].hit << setw(5) << players[i].avg;
}
cout << " " << endl;
cout << "Totals " << totalAB << " " << totalHit << " " << totalAvg << endl;
}
You are dividing an int by an int, which is calculated as an int, and storing it in a double. What you have to do is explicitly cast at least one of your int values to a double first, like this:
void calculateAvg(Record players[], int size)
{
for (int i = 0; i < size; i++)
{
players[i].avg = players[i].hit / (double) players[i].AB;
}
}

Using arrays and strings together

So I'm trying to create an array that contains some user inputted names, and then associate those names with letter grades from tests (ex: A, B, C, D, F). My question is, how would I use an array to accept the user inputted names?
EDIT:
Sorry this is a bit long, I don't know what part to put that would help out. Totally new to C++ and I can't seem to find anything online regarding the matter, lol.
Here is some code. This program currently asks the user for test scores, then displays and drops the lowest test score, and finally, calculates the average of the scores without the lowest one. The end goal is to ask the user for 5 students names, and 4 scores for each student, then dropping the lowest score for each student and calculating the averages of ALL scores inputted regardless of student.
#include <iostream>
#include <string>
using namespace std;
void getScore(int &);
int findLowest(int [], int);
void calcAverage(int [], int);
int main () {
const int NUM_SCORES = 5;
int scores[NUM_SCORES];
cout << "Welcome to test averages." << endl;
cout << "Please enter scores for " << NUM_SCORES << " students." << endl;
cout << endl;
for (int i = 0; i < NUM_SCORES; i++) {
getScore(scores[i]);
}
for (int i = 0; i < NUM_SCORES; i++) {
cout << "Score " << (i + 1) << ": " << scores[i] << endl;
}
cout << endl;
cout << "The lowest of these scores is " << findLowest(scores, NUM_SCORES) << endl;
calcAverage(scores, NUM_SCORES);
return 0;
}
void getScore(int & s) {
s = -1;
cout << "Please enter a test score: ";
cin >> s;
while (s < 0 || s > 100) {
cout << "Score range must be from 0-100" << endl;
cout << "Please re-enter a score: ";
cin >> s;
}
}
int findLowest(int theArray [], int theArraySize) {
int lowest = theArray[0];
for (int i = 1; i < theArraySize; i++) {
if (theArray[i] < lowest) {
lowest = theArray[i];
}
}
return lowest;
}
void calcAverage(int theArray [], int theArraySize) {
int sum = 0;
for (int i = 0; i < theArraySize; i++) {
sum += theArray[i];
}
double average = (sum - findLowest(theArray, theArraySize)) / (theArraySize - 1.0);
cout << "The average is " << average << endl;
}
Try getline from #include <string>
std::string names[5];
for (int i = 0; i < 5; ++i){
getline(std::cin, names[i]);
}

Input Validation: My Program cannot accept negative numbers but it is accepting them and I'm really confused on what to do

#include <iostream>
#include <iomanip>
using namespace std;
// Function Prototype
void sortArray(int array[], int size);
void showArray(const int arr[], int size);
void average(int testScores[], int size);
int main()
{
int *testScores;
int numGrades,count;
cout << "How many grades? " << endl;
cin >> numGrades;
testScores = new int[numGrades];
cout << "Please enter the scores below." << endl;
for (count = 0; count < numGrades; count++)
{
cin >> testScores[count];
}
sortArray(testScores, numGrades);
showArray(testScores, numGrades);
average(testScores, numGrades);
delete[] testScores;
testScores = 0;
system("pause");
return (0);
}
//function for ascending order
int * testScores[];
void sortArray(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (array[count]> array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
// display array function
void showArray(const int arr[], int size)
{
cout << " Scores in ascending order." << endl;
for (int count = 0; count < size; count++)
{
cout << " " << arr[count] << "";
}
cout << endl;
cout << endl;
}
// function to get average of the array
void average(int testScores[], int numGrades)
{
float total = 0.0;
for (int count = 0; count < numGrades; count++)
{
total += testScores[count];
}
float average = total / numGrades;
cout << " This is the average of the scores entered." << endl;
cout << endl;
cout << fixed << showpoint << setprecision(2);
cout << " *** " << average << " ***" << endl;
}
So this program was made to allow students to enter as many test scores as they want and the program will show them in ascending order and then will calculate the average of all test scores. It works wonderful until you enter a negative test score and then it throws the averaging process off. I can't seem to be able to make the program not accept the negative numbers. Any clues or hints would work wonders! Please and Thank You.
You are doing this:-
cin >> testScores[count];
This would accept all integers positive as well as negative. One way is to check the number, if it's positive then insert it into array.