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

#include     // for printf()  
#include    // for pause()  
#include    // for signal()  
#include    // for memset()  
#include  // struct itimeral. setitimer() 
#include  
 #include 

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;countsize;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语言,c++,算法)