C++
#include <iostream>
#include <fstream>
#include <iomanip>
const int NUM_RUNNERS = 5;
const int NUM_DAYS = 7;
// Function to read and store runner names and miles run each day
void readData(std::string runnerNames[], double milesRun[][NUM_DAYS], std::ifstream& inputFile) {
for (int i = 0; i < NUM_RUNNERS; i++) {
inputFile >> runnerNames[i];
for (int j = 0; j < NUM_DAYS; j++) {
inputFile >> milesRun[i][j];
}
}
}
// Function to calculate the average miles run each day
void calculateAverage(double milesRun[][NUM_DAYS], double averages[]) {
for (int j = 0; j < NUM_DAYS; j++) {
double sum = 0.0;
for (int i = 0; i < NUM_RUNNERS; i++) {
sum += milesRun[i][j];
}
averages[j] = sum / NUM_RUNNERS;
}
}
// Function to output the results
void outputResults(std::string runnerNames[], double milesRun[][NUM_DAYS], double averages[]) {
std::cout << std::setw(10) << "Name";
for (int j = 0; j < NUM_DAYS; j++) {
std::cout << std::setw(8) << "Day " << j + 1;
}
std::cout << std::endl;
for (int i = 0; i < NUM_RUNNERS; i++) {
std::cout << std::setw(10) << runnerNames[i];
for (int j = 0; j < NUM_DAYS; j++) {
std::cout << std::setw(8) << std::fixed << std::setprecision(2) << milesRun[i][j];
}
std::cout << std::endl;
}
std::cout << std::setw(10) << "Average";
for (int j = 0; j < NUM_DAYS; j++) {
std::cout << std::setw(8) << std::fixed << std::setprecision(2) << averages[j];
}
std::cout << std::endl;
}
int main() {
std::string runnerNames[NUM_RUNNERS];
double milesRun[NUM_RUNNERS][NUM_DAYS];
double averages[NUM_DAYS];
// Open the input file
std::ifstream inputFile("ch8_Ex12Data.txt");
if (!inputFile) {
std::cerr << "Error: Cannot open the input file." << std::endl;
return 1;
}
// Read and store the data
readData(runnerNames, milesRun, inputFile);
// Calculate the average miles run each day
calculateAverage(milesRun, averages);
// Output the results
outputResults(runnerNames, milesRun, averages);
// Close the input file
inputFile.close();
return 0;
}