使用 C 从传感器获得的值中获取平均值
好的,我得到这个代码来进行平均:(用 C 编写)
.
.
int sum[3];
int j;
int avg;
for(;;) //infinite loop
{
for(j=0;j<3;j++){
i = ReadSensor(); // function that keeps saving sensor values as int i
sum[j]=i;
}
avg=sum[0]+sum[1]+sum[2]+sum[3];
printf("Sonar: %d \r \n", avg >> 2);
}
.
.
这是正确的吗?我移动 2 以除以 avg / 2^(2) 即 4 问题是我期望值约为 15,但我得到的值约为 8--9 ..我不确定为什么会发生这种情况?
基本上传感器的读数在 15-17 之间波动,我想获得平均值而不是打印噪声值。我的代码正确吗?那为什么我会得到错误的输出!?
Ok so I get this code to do the averaging : (written in C )
.
.
int sum[3];
int j;
int avg;
for(;;) //infinite loop
{
for(j=0;j<3;j++){
i = ReadSensor(); // function that keeps saving sensor values as int i
sum[j]=i;
}
avg=sum[0]+sum[1]+sum[2]+sum[3];
printf("Sonar: %d \r \n", avg >> 2);
}
.
.
Is this correct ? im shifting by 2 to divide by avg / 2^(2) which is 4
The problem is im expecting a value of about 15, however I get about 8--9 .. Im not sure why this is happening ?
Basically the sensor's readings fluctuate between 15-17, I want to get an average instead of printing noise values. Is my code correct ? Then why do I get wrong outputs !?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看起来您的脚本仅捕获三个值(j=0、j=1、j=2),然后除以四。
Looks like your script only captures three values (j=0, j=1, j=2), then divides by four.
您遇到了一些问题,这里有一些建议:
for
循环更改为:对于(j = 0;j < 4;j++)。
sum
是一个包含 3 个元素的数组,但在计算avg
时,您正在访问超出数组末尾的元素 1 (sum[3])。这将导致未定义的行为。由于这个原因和上述原因,
sum
应声明为char sum[4]
。sum
不需要是数组,它可以简单地是int
。int
除以 4,请使用除法运算符。编译器应该比您更擅长针对您的特定架构优化代码。这就是您的代码现在的样子,具体取决于您是否需要保留数组:
或者
You have a few problems, here are some suggestions:
for
loop to:for (j = 0; j < 4; j++)
.sum
is an array of 3 elements, yet you're accessing an element 1 past the end of the array when calculatingavg
(sum[3]
). This will cause undefined behaviour.sum
should be declared aschar sum[4]
for this reason and the one above.sum
does not need to be an array in the above example, it can simply be anint
.int
by 4, use the division operator. The compiler should be better at optimizing the code for your particular architecture than you.This is how your code could now look, depending on whether you need to keep an array or not:
OR
难道这不
应该是
循环以及声明
int sum[3];
意味着我们只尝试存储 3 个值。现在如果你想要 4 并且可以使用除法运算符。有新的代码应该替换提到的行
Isn't this
should be
as the loop as well declaration
int sum[3];
means we are trying to store only 3 values.Now if you want 4 and ok with divide operator. There are the new code which should replace the mentioned lines
从传感器读取的值的数量需要两次。首先,控制
for
循环的迭代次数。其次,作为总和的除数。引入一个变量(例如,N
)来捕获它。此外,通过移位进行除法听起来也不正确,因为这将传感器的读数数量限制为 2 的幂。
The number of values read from sensor is required twice. First, to control the number of iterations of
for
loop. Second, as the divisor of sum. Introduce a variable (say,N
) to capture that.Also, the division by shifting does not sound right, because that restricts the number of readings from the sensor to power of two.