Tuesday, July 14, 2009

C++ Assistance, Involving reading file, calculating average, sum (running total), amount of numbers?

I also couldn't figure out how do do this one. It's the last one I have to do, I promise ;). It involves doing stuff with a text file (which I uploaded onto the internet).





The question goes like this:





The Student Cd contains a file named random.txt [I uploaded it to http://d01.megashares.com/?d01=3251418]. This file contains a long list of random numbers. Copy the file to your hard drive and then write a program that opens the file, reads all the numbers from the file, and calculates the following:


A) The number of numbers in the file


B) The sum of all the numbers in the file ( a running total)


C) The average of all the numbers in the file





The program should display the numbers of numbers found in the file, the sum of the numbers, and the average of the numbers.





I really appreciated the help, I wish they had more examples in the book for this stuff. Thanks for taking the time.

C++ Assistance, Involving reading file, calculating average, sum (running total), amount of numbers?
Here you go:





// For this program to work, you have to place the random.txt


// file in the same folder where your program is. Otherwise,


// change the location of the file below





// I am also assuming that you can use arrays. Let me know if


// you have to use linked lists.





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;





using namespace std;





int main()


{


const int MAX_SIZE = 210;


ifstream inFile;


int number;


int array[MAX_SIZE];


int currentIndex = -1;


int sum = 0;





inFile.open("random.txt");





if(!inFile.fail())


{


while(inFile %26gt;%26gt; number %26amp;%26amp; currentIndex %26lt; MAX_SIZE)


{


currentIndex++;


array[currentIndex] = number;


sum += number;


}


inFile.close();





cout %26lt;%26lt; "The file contains: (" %26lt;%26lt; currentIndex + 1 %26lt;%26lt; ") numbers" %26lt;%26lt; endl;





cout %26lt;%26lt; "The sum of all numbers is: " %26lt;%26lt; sum %26lt;%26lt; endl;





cout %26lt;%26lt; "The average is: " %26lt;%26lt; (double) sum / (double) (currentIndex + 1) %26lt;%26lt; endl;


}





else


{


cout %26lt;%26lt; "Couldn't open random.txt" %26lt;%26lt; endl;


}





return 0;


}
Reply:I guess you don't want us to do your homework for you, please specify what you don't know to do here.


Hints:


File IO read in:


http://www.cplusplus.com/doc/tutorial/fi...


have two variables: int counter = 0, sum = 0;


for every new number counter++;


for every new number sum += number;


A is counter


B is sum


C is sum / counter


No comments:

Post a Comment