This program is calculating and displaying the average of 3 groups of numbers in output file. Data is arranged in file so each group of numbers is preceded by number of data items in each group. It works for 2nd & 3rd group but calculation for 1st group is wrong. Thanks for your help!

//numbers.cpp                     
#include <iostream>
#include <fstream.h>
#include <stdlib.h>
using namespace std;
int main()
{
int numb, tot, count, sum;
float avg;

ifstream innumb;
ofstream outnumb;

innumb.open("innumb.txt");
outnumb.open("outnumb.txt");

 if (innumb.fail())
  {
     cout<<"Output file doesn't exist!";
     exit(1);
  }
   while (!innumb.eof())
     {
	innumb>>numb;
	count = numb;
      for (tot=0; tot<count; tot++)
       {
     innumb>>numb;
     sum = sum+ numb;
       }
     avg = sum/count;
     outnumb<<"The average of this group is: "<<avg<<endl;
	sum =0;
       avg=0;
    }
 system("PAUSE");
 return 0;
}  
//This is the run i get:  
//The average of this group is: 4.01863e+008  
//The average of this group is: 86
//The average of this group is: 75

<< moderator edit: added [code][/code] tags >>

Recommended Answers

All 2 Replies

Change this:

int numb, tot, count, sum;

to this:

int numb, tot, count, sum = 0;

sum was uninitialized for the first run, but after the first run you set it to 0, so the second and third runs work properly.

commented: You Rock ;) +1

Thank you, it worked

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.