-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavg_num.c
64 lines (58 loc) · 1.05 KB
/
avg_num.c
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
#include <stdlib.h>
#include "avg_num.h"
/**
* Calculate the average of `num`.
*/
static int calculate_average(avg_num_t * num)
{
int i, sum = 0;
for (i = 0; i < num->length; i++)
{
sum += num->values[i];
}
return sum / num->length;
}
/**
* Create and allocate a new average number structure.
*/
void avg_num_create(avg_num_t * num, int length)
{
if (num == 0)
{
num = (avg_num_t *) malloc(sizeof(avg_num_t));
}
num->values = calloc(length, sizeof(int));
num->length = length;
avg_num_clear(num);
}
/**
* Add a number to the average number and return the
* newly calculated average.
*/
int avg_num_add(avg_num_t * num, int n)
{
if (num->used < num->length)
{
num->used++;
}
num->values[num->idx++] = n;
if (num->idx >= num->length)
{
num->idx = 0;
}
num->avg = calculate_average(num);
return num->avg;
}
/**
* Clear all values and reset the average and index values
* to zero.
*/
void avg_num_clear(avg_num_t * num)
{
int i;
for (i = 0; i < num->length; i++)
{
num->values[i] = 0;
}
num->avg = num->idx = num->used = 0;
}