-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaverage.cpp
More file actions
executable file
·91 lines (73 loc) · 1.54 KB
/
Copy pathaverage.cpp
File metadata and controls
executable file
·91 lines (73 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<iostream>
using namespace std;
class MovingAverage
{
public:
virtual float getAverage() = 0;
virtual void addSample(float val) = 0;
};
class SimpleMovingAverage : public MovingAverage
{
public:
SimpleMovingAverage(int size);
virtual ~SimpleMovingAverage();
float getAverage();
void addSample(float val);
private:
float* m_samples;
float m_total;
int m_nextLoadPos;
int m_Size;
bool isFullLoad;
};
SimpleMovingAverage :: SimpleMovingAverage(int size)
{
m_samples = new float[size];
m_Size = size;
m_total = 0.0f;
m_nextLoadPos = 0;
isFullLoad = false;
}
SimpleMovingAverage :: ~SimpleMovingAverage()
{
delete [] m_samples;
}
float SimpleMovingAverage :: getAverage()
{
int count = m_Size;
if(!isFullLoad)
{
count = m_nextLoadPos;
}
return m_total / count;
}
void SimpleMovingAverage :: addSample(float val)
{
if(!isFullLoad)
{
m_samples[m_nextLoadPos] = val;
m_total += val;
m_nextLoadPos++;
if(m_nextLoadPos == m_Size)
{
isFullLoad = true;
m_nextLoadPos = 0;
}
}
else
{
m_total -= m_samples[m_nextLoadPos];
m_total += val;
m_samples[m_nextLoadPos] = val;
m_nextLoadPos =( m_nextLoadPos + 1) % m_Size;
}
}
int main(int argc, char** argv)
{
MovingAverage* pAverage = new SimpleMovingAverage(5);
for(int i = 1; i < 8; i++)
{
pAverage->addSample(i);
cout << pAverage->getAverage() << endl;
}
}