Originally Posted by
Rod Micael
I thought the movinavg has elements because its dependent on the temperature on this loop part:
Code:
if (i=0)
{ movingavg[i]=temperature[i];
Think post #11 said it best
Question about a certain code with the C++ syntax
To repeat something else Jim said - it's far far easier to figure out what's wrong if you use a debugger. I see you've built your code with both Visual Studio and GCC -- both Visual Studio and gdb would have been able to tell you the exact line with the problem.
If you get friendly with a debugger, you'll spend a lot less time being confounded by weird logic errors. Honestly, it's worth the time.
Couple of other comments:
Code:
if (i=0)
....
else if (i=numberofterms-1)
These should be "==" not "=".
I'm a bit confused about what you want your program to do. Say the user wants to input 5 values. Do you intend them all to be input, then the moving averages are computed after input is finished? Or do you want to calculate the moving averages on the fly as the user enters the data?
This loop looks like it's meant to calculate averages for all the data:
Code:
for (int j=0; j<numberofterms-number_of_elements_avg; j++)
{
// j - number_of_elements_avg/2.0
unsigned int start = j - number_of_elements_avg/2;
average = accumulate(temperature.begin() + start, temperature.begin() + j + number_of_elements_avg/2 + 1, 0.0) / (number_of_elements_avg + 1);
}
but this loop is nested inside your for loop for input, so will be run every time the user enters a number. If you want to do it 'on the fly' you don't need a second loop: as soon as you have number_of_elements_avg elements you can do an accumulate using 'i' to work out the start and end. However that'd mean you'd get (if I put in 10,20,30,40,50 for 3 avg points):
Code:
element value average
1 10 10
2 20 20
3 30 (10+20+30)/3
4 40 (20+30+40)/3
5 50 (30+40+50)/3
and it looks like you want
Code:
element value average
1 10 10
2 20 (10+20+30)/3
3 30 (20+30+40)/3
4 40 (30+40+50)/3
5 50 50
In which case you do need a second loop, but you don't want it inside your input loop.
Once you've fixed your array allocation I think you'll get another crash:
Code:
for (int j=0; j<numberofterms-number_of_elements_avg; j++)
{
// j - number_of_elements_avg/2.0
unsigned int start = j - number_of_elements_avg/2;
If j=0 and number_of_elements_avg=3, start is 0 - (3/2) = 0-1 = -1. Since start is unsigned, you'll get the unsigned representation of the signed number -1, which is probably around about 4 billion. Not going to work!
You could change the initial value of j, or change the calculation of start and end.