我试图在不使用数组或动态分配的情况下平滑输入数据(真正的正数)。可能吗?
结束条件是用户输入负数。例如:
input: 1 2 3 4 5 -1
output: 1.5 2 3 4 4.5
最佳答案
您可以使用移动平均线来做到这一点。最简单的形式
const int smooth_factor = 3; // the higher the value the more smooth it is.
int samples = 0;
int total = 0; // make long or long long if danger of overflow.
int smoothed(int new_sample)
{
if (samples == smooth_factor)
{
total -= total / smooth_factor;
samples -= 1;
}
total += new_sample;
samples += 1;
return total / samples;
}
在实践中,您可能会通过使用 2 的幂 smooth_factor 并使用移位操作而不是除以 smooth_factor 来提高效率。 如果您愿意预播 total 和 num 个样本,您也可以去掉 if 语句。
const int smooth_factor = 16; // the higher the value the more smooth it is.
int total = 129; // e.g. 129 = sum of first 16 samples
int smoothed(int new_sample)
{
total -= total >> 4;
total += new_sample;
return total >> 4;
}
如果您要对多个值进行平滑处理,那么您可以删除其中一个变化而不会产生显着影响(但我将把它留作练习)。
关于c - 在不使用数组或动态分配的情况下平滑输入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13417711/