C++ Average Calculation Function Returning 0 [closed] - c++

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;
}
}

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 :|

Array search and unique value addition

(Sorry if this is formatted terribly. I've never posted before.)
I've been working on a program for class for a few hours and I can't figure out what I need to do to my function to get it to do what I want. The end result should be that addUnique will add unique inputs to a list of its own.
#include <iostream>
using namespace std;
void addUnique(int a[], int u[], int count, int &uCount);
void printInitial(int a[], int count);
void printUnique(int u[], int uCount);
int main() {
//initial input
int a[25];
//unique input
int u[25];
//initial count
int count = 0;
//unique count
int uCount = 0;
//user input
int input;
cout << "Number Reader" << endl;
cout << "Reads back the numbers you enter and tells you the unique entries" << endl;
cout << "Enter 25 positive numbers. Enter '-1' to stop." << endl;
cout << "-------------" << endl;
do {
cout << "Please enter a positive number: ";
cin >> input;
if (input != -1) {
a[count++] = input;
addUnique(a, u, count, uCount);
}
} while (input != -1 && count < 25);
printInitial(a, count);
printUnique(u, uCount);
cout << "You entered " << count << " numbers, " << uCount << " unique." << endl;
cout << "Have a nice day!" << endl;
}
void addUnique(int a[], int u[], int count, int &uCount) {
int index = 0;
for (int i = 0; i < count; i++) {
while (index < count) {
if (u[uCount] != a[i]) {
u[uCount++] = a[i];
}
index++;
}
}
}
void printInitial(int a[], int count) {
int lastNumber = a[count - 1];
cout << "The numbers you entered are: ";
for (int i = 0; i < count - 1; i++) {
cout << a[i] << ", ";
}
cout << lastNumber << "." << endl;
}
void printUnique(int u[], int uCount) {
int lastNumber = u[uCount - 1];
cout << "The unique numbers are: ";
for (int i = 0; i < uCount - 1; i++) {
cout << u[i] << ", ";
}
cout << lastNumber << "." << endl;
}
The problem is my addUnique function. I've written it before as a for loop that looks like this:
for (int i = 0; i < count; i++){
if (u[i] != a[i]{
u[i] = a[i]
uCount++;
}
}
I get why this doesn't work: u is an empty array so comparing a and u at the same spot will always result in the addition of the value at i to u. What I need, is for this function to scan all of a before deciding whether or no it is a unique value that should be added to u.
If someone could point me in the right direction, it would be much appreciated.
Your check for uniqueness is wrong... As is your defintion of addUnique.
void addUnique(int value, int u[], int &uCount)
{
for (int i = 0; i < uCount; i++){
if (u[i] == value)
return; // already there, nothing to do.
}
u[uCount++] = value;
}

Data cleanup array

I need to write a program that cleans up two arrays with 12 scores and gets rid of the "bonus scores" (where the denominator is 0). I've looked at similar problems, but I'm at a point in which there's three main problems that either no one seems to have or haven't been addressed. the first one is when declaring the new (not bonus) arrays in main it requires that I enter a constant value, however; the size of the arrays must change for the clean_data function to work.
the second one is when calling clean_data in main it marks "deno" and "num" as an error saying that "argument of type int * is incompatible with parameter of type int**", and the last one says that the function clean_data cannot convert argument 1 from int[12] to int*[].
I've been poking at this code for 3 days and looked at my professor's notes and textbook and can't find a way to fix it. please help.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
//prototypes for functions
void read_data(int nume[], int deno[], int size);
void report_data(int nume[], int deno[], int size);
void report_overall_grade(int nume[], int deno[], int size);
//Data cleanup
void clean_data(int *nume[], int *deno[], int size, int *notBonusNum[], int *notBonusDen[], int &newSize);
int main()
{
//declare constat, arrays, and variables;
const int NUM_GRADES = 12;
int nume[NUM_GRADES];
int deno[NUM_GRADES];
int newSize = 12;
int notBonusNum[newSize];
int notBonusDen[newSize];
//call functions
read_data(nume, deno, 12);
cout << "Original scores: " << endl;
cout << fixed << showpoint << setprecision(1);
report_data(nume, deno, 12);
system("pause");
system("cls");
report_overall_grade(nume, deno, 12);
//Data cleanup
clean_data(nume, deno, 12, notBonusNum, notBonusDen, newSize);
cout << "There are " << newSize << " scores that aren't bonuses:" << endl;
report_data(notBonusNum, notBonusDen, newSize);
system("pause");
return 0;
}
//function definitions
void read_data(int nume[], int deno[], int size)
{
//open file
ifstream inputFile;
inputFile.open("scores.txt");
if (inputFile.fail())
{
cout << "File does not exist." << endl;
system("pause");
exit(1);
}
//read data
int count;
for (count = 0; count < size; count++)
{
inputFile >> nume[count];
inputFile >> deno[count];
}
inputFile.close();
}
void report_data(int nume[], int deno[], int size)
{
int count;
int number = 1;
for (count = 0; count < size; count++)
{
if (deno[count] > 0)
{
int numerator = nume[count];
int denominator = deno[count];
double percent = (double)numerator / denominator * 100;
cout << "Score " << number << " is " << numerator << " / " << denominator << " = " << percent << "%." << endl;
}
else
{
cout << "Score " << number << " is " << nume[count] << " / " << deno[count] << " = Bonus Points!" << endl;
}
number++;
}
}
void report_overall_grade(int nume[], int deno[], int size)
{
int count;
int totalNum = 0;
int totalDeno = 0;
double overallGrade;
for (count = 0; count < size; count++)
{
totalNum += nume[count];
totalDeno += deno[count];
}
cout << "Total points earned: " << totalNum << endl;
cout << "Total points possible: " << totalDeno << endl;
overallGrade = (double)totalNum / totalDeno * 100;
cout << "Overall grade: " << overallGrade << endl;
}
//Data cleanup
void clean_data(int *nume[], int *deno[], int size, int *notBonusNum[], int *notBonusDen[], int &newSize)
{
int count;
for (count = 0; count < size; count++)
{
int count2 = 0;
if (deno[count] != 0)
{
notBonusNum[count2] = nume[count];
notBonusDen[count2] = deno[count];
newSize--;
count2++;
}
}
}

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.