Microsoft Interview Question
Software Engineer / DevelopersThis is correct logically but for the initialization steps.
You are reinitializing the static sount and average to zero which makes you lose the previous values.
So you need to remove " =0 " in the first 2 lines
Instead of static average, use static sum. If I'm not mistaken, the idea is to accumulate the numbers and then return the average.
double computeAverage(double newVal)
{
static int count=1;
static double sum=0;
sum+=newVal;
return sum/count++;
}
I believe a float allows a smaller mantissa so you may have a buffer overflow sooner.
double computeAverage(double newVal) {
- srihari January 06, 2006static int count=0;
static float average=0;
average = (average * count + newVal)/++count;
return average;
}
Every time the average is computed from the previous average and count. count is the number of values seen so far. Since we need the average and count to persist between function calls, we can declare them static.