[英]Average for each three consecutive numbers in an array
How can I calculate the average for each three consecutive numbers in an array and then to print each result?如何计算数组中每三个连续数字的平均值,然后打印每个结果? (in C)
(在 C 中)
I tried to do this.我试图做到这一点。
#include <stdio.h>
int main() {
int n,v[100],i;
float average;
int sum=0;
scanf("%d",&n);
for (i = 0; i < n; ++i) {
scanf("%d",&v[i]);
}
for(i=0;i<n;i+=3) {
sum=v[i]+v[i+1]+v[i+3];
average=sum/3;
printf("%.2f ", average);
}
return 0;
}
sum/3
is an int
division with an int
quotient. sum/3
是具有int
商的int
除法。
To also have a fractional part, use floating point division.要也有小数部分,请使用浮点除法。
// average=sum/3;
average = sum / 3.0f;
for(i=0;i<n;i+=3) { sum=v[i]+v[i+1]+v[i+3];
risks accessing data out of v[]
bounds.访问数据超出
v[]
范围的风险。 v[i]+v[i+1]+v[i+3]
are not consecutive. v[i]+v[i+1]+v[i+3]
不连续。 I'd expect v[i]+v[i+1]+v[i+2]
我希望
v[i]+v[i+1]+v[i+2]
for (i = 0; i + 2 < n; i += 3) {
sum = v[i] + v[i+1] + v[i+2];
No good reason to use float
.没有充分的理由使用
float
。 Use double
unless float
is needed for space/ maybe speed, etc.除非空间需要
float
/可能是速度等,否则请使用double
精度数。
Also avoid overflow and precision loss.还要避免溢出和精度损失。
for(int i = 0; i+2 < n; i += 3) {
double sum = 0.0 + v[i] + v[i+1] + v[i+2]; // Addition here uses FP math.
double average = sum/3.0;
printf("%.2f ", average);
}
Better code writes a '\n'
at the end and does not end with a dangling " "
.更好的代码在最后写一个
'\n'
并且不以悬空的" "
结尾。
const char *separator = "";
for(int i = 0; i+2 < n; i += 3) {
...
printf("%s%.2f ", separator, average);
separator = " ";
}
printf("\n");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.