我正在尝试计算数组中特定行的平均值。 例如,数组的格式如下所示:
float Array[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,...20}
我想计算数组中前5个数字的平均值,然后计算接下来的5个数字的平均值,等等......将它们存储到另一个只有这些数字的平均值的数组中。
到目前为止,这是我的代码
float average_values[4];
for (int a = 0; a < 4; a++){ //20 elements in array divided by 5 = 4
float sum = 0;
for (int b = 0; b < (20 / 4); b++){
sum = sum + scores[b];
}
average_values[i] = sum / (20 / 4);
}
答案 0 :(得分:1)
#include <stdio.h>
int main()
{
int scores[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20};
float average_values[4];
for (int a = 0; a < 4; a++)
{ //20 elements in array divided by 5 = 4
float sum = 0;
for (int b = 0; b < (20 / 4); b++)
sum = sum + scores[b+a*5]; // THIS IS THE BIT YOU'D MISSED
average_values[a] = sum / (20 / 4);
}
}
答案 1 :(得分:0)
暂时保留当前帖子中的所有拼写错误
我认为您在填写average_values
数组时遇到问题。
因此假设scores
数组为5列和4行的矩阵,
所以你的内循环应该是这样的:
for (int b = 0; b < 5; b++){
sum = sum + scores[ a*5 + b];
//~~~ Correct index for next sets
}
答案 2 :(得分:0)