Static local variables- C programming

1) Write the definition of a function named averager that receives a double parameter and return-- as a double -- the average value that it has been passed so far. So, if you make these calls to average, averager(5.0), averager(15.0), averager(4,3), the values returned will be (respectively): 5.0, 10.0, 8.1.

2) Write the definition of a function named newbie that receives no parameters and returns 1 the first time it is invoked (when it is a "newbie"), and that returns 0 every time that it is invoked after that.
1
2
3
4
5
6
7
double averager(double p) { 
  static unsigned n_elements;
  static double prev_avg;
  prev_avg = (n_elements * prev_avg + p) / (n_elements + 1);
  n_elements ++;
  return prev_avg;
}


But it makes more sense to do something like
1
2
3
4
5
6
7
8
9
10
# include <functional>
std::function <double(double)> make_averager() {
  unsigned n = 0; 
  double avg = 0.0;
  return [=] (double p) mutable {
    avg = (n * avg + p) / (n + 1);
    n++; 
    return avg;
  };
}
Last edited on
I figured out the second one

The code for it was :

1
2
3
4
int newbie(void){
static c=0;
return !(c++);
}



Im still stuck on #1 though
What information do you need to calculate the average at any step?

How do you calculate the information when you receive a new value that is included in the average?

What is the initial value for the information before the function is called the first time?

When you know that information, you can write your function.

btw, @mbozzi's solution is a little bit more complex that in needs to be. Plus, he should not be doing your homework for you anyway.
After getting the second one I eventually figured out the first

1
2
3
4
5
6
7
double averager(double a){
static double s=0.0;
static c;
s+=a;
c++;
return s/c;
} 
You actually have 2 problems in the code you pasted. Both are in line 3.

First of all, you never declared the type of c, just that it is static. Years ago, before C was standardized everything that was declared was an int unless stated otherwise. Now you must declare the type of every variable. Some compilers may allow you to implicitly declare an int variable, but you should get into the habit of declaring all of your variables correctly.

The second issue is you never initialized c. If the memory location where c is created happens to have garbage in it, you will have weird results when you create averages.

So line 3 should be:
static int c = 0;
Last edited on
Topic archived. No new replies allowed.