Create a program that find the average and sum (total) of all the numbers store
ID: 3672611 • Letter: C
Question
Create a program that find the average and sum (total) of all the numbers store in a text file using the following specification.
Create a function named callCount that accepts no arguments (parameters) and returns the number of times it has been called. For example, the first time the function is called, it returns 1, the second time it returns 2, and so on. Hint: use a static variable to hold the call count.
Create a function named runningTotal that accepts a single floating-point parameter with a default value of zero. Every time the function is called, it adds the given number to a running total and returns the floating-point total. Hint: use 1 static variable to store the total.
Create a function named cumulativeAverage that accepts a single floating-point parameter with a default value of zero. The function calculates and returns the average of the numbers from the current and all previous calls to it. Use your runningTotal function and callCount functions to calculate the average (the average is the total divided by number of values).
Create a function named averageValueFromFile that accepts one parameter, the file name as a constant reference to a string. The function opens the file specified by the parameter. Use ifstream's is_open() member function to check if the file was properly opened. If not, print an error message to the screen and return 0. Otherwise, read all the numbers from the file and use your cumulativeAverage to calculate the average. After calculating the average with all the numbers from the file, return the average. This function should not print anything to the screen, unless there was an error opening the file.
The main function should prompt the user for a filename. Call averageScoresFromFile and then runningTotal to calcualte the values to be displayed. The average and total of all the numbers in the file should be displayed with 2 decimal places.
Explanation / Answer
Create a program that find the average and sum (total) of all the numbers store in a text file using the following specification.
#include <iostream>
#include <cmath>
#include <math.h>
#include <fstream>
#include <string>
#include <numeric>
using namespace std;
int main()
{
const int nNumStudents = 5;
int anScores[nNumStudents] = { 84, 92, 76, 81, 56 };
int nTotalScore = 0;
for (int nStudent = 0; nStudent < nNumStudents; nStudent++)
nTotalScore += anScores[nStudent];
double dAverageScore = static_cast<double>(nTotalScore) / nNumStudents;
cout << "The average score was " << dAverageScore << endl;
getchar();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.