代码解释
- 定义宏:使用
#define FILTER_TYPE
来定义滤波数值的类型,可以轻松改变滤波数值的类型。#define FILTER_SIZE
定义滤波数组的大小。 - 结构体:定义一个结构体
MedianFilter
,包含一个固定大小的数组data
和当前数据计数count
。 - 初始化函数:
MedianFilter_init
函数用于初始化滤波器,设置计数为0。 - 处理函数:
MedianFilter_process
函数处理输入的数值,更新滤波数组,并计算中值。 - 主函数:测试代码,初始化滤波器并处理一组数值,输出每次添加新值后的中值。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILTER_TYPE int // 可以通过宏定义改变滤波数值的类型
#define FILTER_SIZE 5 // 定义滤波数组的大小
typedef struct {
FILTER_TYPE data[FILTER_SIZE];
size_t count;
} MedianFilter;
void MedianFilter_init(MedianFilter *filter) {
filter->count = 0;
}
FILTER_TYPE MedianFilter_process(MedianFilter *filter, FILTER_TYPE value) {
if (filter->count < FILTER_SIZE) {
filter->data[filter->count++] = value;
} else {
memmove(filter->data, filter->data + 1, (FILTER_SIZE - 1) * sizeof(FILTER_TYPE));
filter->data[FILTER_SIZE - 1] = value;
}
FILTER_TYPE sorted[FILTER_SIZE];
memcpy(sorted, filter->data, filter->count * sizeof(FILTER_TYPE));
for (size_t i = 0; i < filter->count - 1; ++i) {
for (size_t j = i + 1; j < filter->count; ++j) {
if (sorted[i] > sorted[j]) {
FILTER_TYPE tmp = sorted[i];
sorted[i] = sorted[j];
sorted[j] = tmp;
}
}
}
return sorted[filter->count / 2];
}
int main() {
MedianFilter filter;
MedianFilter_init(&filter);
FILTER_TYPE values[] = {10, 20, 30, 40, 50, 60, 70};
size_t num_values = sizeof(values) / sizeof(values[0]);
for (size_t i = 0; i < num_values; ++i) {
FILTER_TYPE median = MedianFilter_process(&filter, values[i]);
printf("Added %d, Median: %d\n", values[i], median);
}
return 0;
}