I need help on what to do next in a program. Here are the directions, and what I have so far. I just need help on coming up with how to write the function to calculate the "low,' and I can do the rest. Thanks is advance.
You are to write a program to read an unknown number of real (float) values from a file and output their distribution. The distribution classes are as follows.
Low: Count of values < average –5
Mid: Count ofvalues in range [average-5,average+5]
High: of values > average +
I suggest not reading from the file every time you want to get a number to compute some value. Read the entire file once, and then do whatever you want with the read data. This solution assumes the floats are separated by whitespace characters in the file.
#include <iostream>
#include <fstream>
#include <string>
bool readFileToArray(std::string filename, float array[], constint size) {
std::ifstream file(filename.c_str(), std::ios::binary);
if (!file) {
returnfalse;
}
for (int i = 0; i < size && file >> array[i]; ++i);
file.close();
returntrue;
}
float computeAverage(float array[], constint size) {
float average = 0.0;
for (int i = 0; i < size; ++i) {
average += array[i];
}
average /= (float)size;
return average;
}
int main() {
constexprint size = 4;
float array[size] = {};
std::string filename = "floats.txt";
if (!readFileToArray(filename, array, size)) {
std::cout << "There was an error!" << std::endl;
return 1;
}
float average = computeAverage(array, size);
std::cout << average << std::endl;
return 0;
}
In the case that the file contains less floats than the size of the array - let's say the array has four floats, but the file only has three - the average is still computed, and the fourth, missing number is treated as a zero. This is because our array has been default initialized, so any element that hasn't been overwritten by a read float will retain it's initial value of zero.