C语言实现的滑动窗口求平均值

#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;
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值