English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

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.

2007-03-28 14:57:09 · 2 answers · asked by Stash O 3 in Computers & Internet Programming & Design

Well, I don't if you do them. I may actually prefer that. I learn through examples, and this is due tomorrow so I dont' have much time.

2007-03-28 18:55:51 · update #1

2 answers

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
#include

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 >> number && currentIndex < MAX_SIZE)
{
currentIndex++;
array[currentIndex] = number;
sum += number;
}
inFile.close();

cout << "The file contains: (" << currentIndex + 1 << ") numbers" << endl;

cout << "The sum of all numbers is: " << sum << endl;

cout << "The average is: " << (double) sum / (double) (currentIndex + 1) << endl;
}

else
{
cout << "Couldn't open random.txt" << endl;
}

return 0;
}

2007-03-28 21:41:50 · answer #1 · answered by Silver_Sword 3 · 1 0

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/files.html
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

2007-03-29 01:51:03 · answer #2 · answered by eyal b 4 · 1 0

fedest.com, questions and answers