Hey guys, total C++ n00b here. I am working on assignment that has me totally stumped. I need to open and read a file using containing 20 integers,then I need to add them all up, and find the average and do this while using loops.I've got the first part working properly for displaying the integers, but I am totally stumped with finding the sum of the integers and the average.Any help is greatly appreciated! Here's what I've got so far:
Your assignment could be done in under 20 lines of code. Any help at all could result in actually doing the assignment for you...
Here's a suggestion, instead of using multiple loops, do everything using the same loop. The reason it isn't working is because after your first loop, you're already at the end of the input file. There's nothing more to read for your other loops.
You are so close, so I will help you out. Notice that I changed sum and num to also be floats. This will give you a more precise average. I used setprecision(2) to output 2 decimal places. It requires the #include <iomanip> that you have already provided.
Instead of using the constant 20, I used your count so this code will produce the average regardless of how many numbers are in the file. You can add some code to alert the user if the file is blank. Also, there is no need to clear a file after you close it so I took that part out.
int count = 0;
float sum = 0;
float num = 0;
float solution = 0;
InFile.open("E:\\CFiles\\DataFile2.txt");
if (InFile)
InFile>>num;
while (InFile)
{
sum=sum+num;
count++;
InFile>>num;
}
if (count > 0)
{
solution=sum/count;
cout<<setprecision(2)<<"The average of all numbers in the file is "
<<solution<<endl;
}
else
// alert the user that no numbers
// were read in
InFile.close();
I guess I'm still pretty confused at the logic in "if" vs "while". Originally I was trying to write it with a while loop and I noticed I when I rewrote the good code above with "while" in place of "if" in front of the count statement the output fails.
What is the rationale behind that?
Also if I wanted to tweak the code to only find the average of the first 12 numbers shouldn't I just be able to change count to "(count<=12)"? That doesn't seem to work...