Hey, Im having trouble writing a function that will take a limited running average from a file. the running average works just fine, its just when i try to limit the input, i just come out to inf. could it possibly be that im using a static double for the sum?

using namespace std;

int limit = 10;
double lavg;

double avgl (double x)
{
static int n=0;
static double s = 0;
if (n<=limit)
{
s+=x;
n++;
s/n;
lavg = s/n;
return lavg;
}
else
{
lavg=(lavg*(limit-(1.0/limit)))+(x*(1.0/limit));
return lavg;
}
}
//for (n=0, s=0; s+=x; n++)
//s*(limit-1/limit))+x*(1/limit)
int main ()
{
                string buffer;
                    string currentPrice1;
                static float currentPrice;
                static double averagesum = 0.0;
                int count;
                ifstream myfile;
                myfile.open ("KSP200OPTCALL_CHE_20100506.txt");
                while (! myfile.eof() )
                {
                                getline(myfile,buffer);
                                cout << buffer << endl;


                        currentPrice1 = buffer.substr (30, 5);
                        currentPrice= atoi(currentPrice1.c_str());
                        currentPrice= currentPrice/100.00;
                        cout << "Current Price: " << currentPrice << endl;
                        cout << "Running Average: " << avgl(currentPrice) << endl;

Test immediately after (not before) reading a line.

while( /*! myfile.eof()*/ getline(myfile,buffer) )
{
    /*getline(myfile,buffer);*/
    // ...
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.