#include <stdio.h> // for printf()
#include <unistd.h> // for pause()
#include <signal.h> // for signal()
#include <string.h> // for memset()
#include <sys/time.h> // struct itimeral. setitimer()
#include <math.h>
#include <stdlib.h>
typedef struct win_buff{
int pos; /* current position */
int size; /* average for size */
int date_buff[32]; /* date*/
}win_buff;
double sliding_window_averaging(win_buff *buf, int get_data)
{
int count = 0;
int sum=0;
buf->date_buff[buf->pos++] = get_data ; //get_data为实时获取的数据
// printf("buf->pos: %d %d \n", buf->pos, get_data);
if(buf->pos==buf->size){
buf->pos=0; //当数据大于数组长度,替换数据组的一个数据 相当于环形队列更新,先进先出!
}
for(count=0;count<buf->size;count++){
sum += buf->date_buff[count];
//printf("sum : %d %d %d\n", sum, buf->date_buff[count], count);
}
return (double)((double)sum/buf->size);
}
int main()
{
int buf[] = {1, 2, 3, 4, 4, 5 ,5 ,5 ,5 ,5 ,5 , 4,4,4,4,4,4,4,5,5};
int len = sizeof(buf)/sizeof(int);
int i = 0;
double avg = 0.0;
win_buff *buff;
buff = (win_buff *)malloc(sizeof(*buff));
memset(buff, 0, sizeof(*buff));
buff->size = 8;
for(i = 0; i < len; i++)
{
avg = filter(buff ,buf[i]);
printf("vag: %f buf[i]:%d len: %d\n", avg,buf[i], len);
}
return 0;
}
C语言实现的滑动窗口求平均值
最新推荐文章于 2024-07-10 17:36:54 发布