I have written two separate programs; Program 1 calculates the average of an array of numbers which has been hard-coded into the program. Program 2 reads an array of numbers from a text file and displays them on the output.
I wish to combine these two programs into one by making Program 1 read the array of numbers from the file and then calculate the average using that instead of the array { 84, 92, 76, 81, 56 } as outlined below. I only wish to display the average in the output, not the number array as Program 2 does.
I have tried to do most of the work, I just need help with modifying the code slightly so it reads the number array from the file and calculates the average. Please include the modified code in your answer.
Yes, eof caused some issues in that it was including the last value twice in the average. In addition, the code that was provided needed some debugging, so the final version is below. Can someone come up with a more efficient method of doing this without eof?
cout << "The last number in this range is: " <<num<< "\n";
cout<< "The sum of this range is: " <<(total-num)<<'\n';
cout<< "The number of items in this range is: "<<x-1<<'\n';
cout<< "The average of this range is: "<<aver<<'\n';
cout<< ""<<'\n';
#include <fstream>
#include <iostream>
int main() {
std::ifstream infile ("cnumbers.txt");
float num;
float total = 0.0f;
unsignedint count = 0;
// While infile successfully extracted numbers from the stream
while(infile >> num) {
total += num;
++count;
}
// don't need the file anymore, close it
infile.close();
// test to see if anything was read (prevent divide by 0)
if (!count) {
std::cerr << "Couldn't read any numbers!" << std::endl;
return 1;
}
// give the average
std::cout << "The average was: " << total/count << std::endl;
// pause the console
std::cin.sync();
std::cin.get();
return 0;
}
Thanks, this worked like a charm. I was wondering if you could tell me how to loop through various files in this manner? e.g. we calculated the average for a file called enumbers.txt; suppose we wanted to calculate the average for a whole bunch of files, e.g. fnumbers.txt, gnumbers.txt, etc.
Is there anyway to do this through a loop without duplicating the code each time with a different file specified?
Also, suppose we wanted to calculate the percentage difference for each number and then store it as an array? What I am trying to do is create a model that can calculate the percentage differences between each subsequent variable, store it as its own array, and then calculate the skew from that using the formula ((n/(n-1)*(n-2))*(Xi-averageX)/standarddeviation^3)).
How do I store percentage changes as a separate array and then calculate the above for them with that formula?