-3

What I am trying to achieve in the following code is to find moving average;

int slots = int ((sr+e)/mst); // finding number of slots


int temp2;
int temp1;

if (temp1 == null) 
{
temp2 = 0;
}

temp2=temp1;   // previously found number of slots
temp1=slots;  // presently found number of slots
double mov_avg = (temp2+temp1)/2; //moving average

The problem is when I compile, I get a warning of temp1 being uninitialised; upon doing a small research, I found that variables do not store null value or zero value on default in C++ when it is uninitialised;

I cannot put a line as temp1 = 0 in the code as its value will be required for the next iteration to be passed on to the temp2 variable; both of which will be required to compute the moving average.

So, basically this a problem for the first time functioning of the above procedure; because if you get past it, the above logic would be sufficient for the moving average calculation. What do you guys think?

Thanks in advance.

ecmadeeasy
  • 17
  • 3
  • It looks like you can make this much simpler by having just `value = (value + nextitem) / 2;` in each iteration. – Kerrek SB Apr 25 '13 at 08:03
  • @KerrekSB: I don't think this is correct. Take the following sample: `90;10;0`. The moving averages over two values will be `50;5` will your formula gives `50;25`. Or did I miss something? – Luc Touraille Apr 25 '13 at 08:15
  • If you already expect the variables to be default initialize to zero why can't you do it manually and get the same affect? It makes no sense to not initialize them before they are used as the behavior is undefined. `int temp1 = 0;` – Captain Obvlious Apr 25 '13 at 08:20

1 Answers1

2

The simplest solution is to initialize your variable with the first value of your sequence:

int prev = getValue();

while (valuesAvailable())
{
    int next = getValue();
    double moving_average = (prev + next) / 2.;
    // use moving_average
    prev = next;
}

Note that I assumed that there was at least one value in your sequence: you may need to do a check before getting the first value to make sure it is actually there.

Luc Touraille
  • 79,925
  • 15
  • 92
  • 137