Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating and implementing functions (C++).
#14
If you have the line
cout << "VARIANCE = " << Variance (inF, numValues, avg, squaresSum) << endl;
in the main program, then the variables need to be declared in the main program.

I see you have Variance() calculating "avg" by itself (doing Sum()/InputCount()). If that is the case, main() doesn't need to give it the average.
Conversely, if main() already calls Sum() and InputCount(), then it can store the result in a variable and pass it to Variance(), who won't need to redo the work.

So, you can have your code either like this:
Code:
float Variance(ifstream &inF);

float Variance(ifstream &inF)
{
    //Start from the beginning of the file - Rewind.
    inF.clear();
    inF.seekg(0L, ios::beg);

    //Variance = sumofsquares/#values - average*average (when numValues>0);
    float variance = 0;
    float avg = Sum (inF) / InputCount (inF);
    variance = SumOfSquares (inF) / InputCount (inF) - avg * avg;
    return variance;
}

int main()
{
   ...
   //Prints the variance of the values in file.
   cout << "VARIANCE = " << Variance (inF) << endl;
}

or you could do it this way

Code:
float Variance(int numValues, float average, float squaresSum);

float Variance(int numValues, float average, float squaresSum)
{
     return squaresSum / numValues - average * average;
}

int main()
{
   int count;
   float avg;
   float squares;

- open files etc -
   count = InputCount(inF);
   avg = Sum(inF) / count;
   squares = SumOfSquares(inF);
  
   //Prints the variance of the values in file.
   cout << "VARIANCE = " << Variance (count, avg, squares) << endl;
}

In the first case, Variance() needs no input (arguments) other than the input file handle. It calls on the other functions to help it do its work, keeping all calculations and intermediate results hidden from the main program.
In the second case, main() "micromanages" the functions, telling each one what to do when, and as a result, Variance() is a much simpler function - just the formula - but it needs all the relevant numbers handed to it.
Reply


Messages In This Thread
Creating and implementing functions (C++). - by SaptaZapta - 2013-09-16, 03:12 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)