所以,假设我有一个2D数组:
int a[WEEK][DAY] = {367, 654, 545, 556, 565, 526, 437,
389, 689, 554, 526, 625, 537, 468,
429, 644, 586, 626, 652, 546, 493,
449, 689, 597, 679, 696, 568, 522,
489, 729, 627, 729, 737, 598, 552};
我如何计算每列的平均值?例如, (367 + 389 + 429 + 449 + 489)/5=424.6等。我已经想出了如何计算每一行的平均值,但我很难为每一列做这个。 这就是我到目前为止所拥有的:
#include <stdio.h>
#define WEEK 5
#define DAY 7
int main() {
/* or int a[][DAY] = {367, 654, 545, 556, 565, 526, 437, */
int a[WEEK][DAY] = {367, 654, 545, 556, 565, 526, 437,
389, 689, 554, 526, 625, 537, 468,
429, 644, 586, 626, 652, 546, 493,
449, 689, 597, 679, 696, 568, 522,
489, 729, 627, 729, 737, 598, 552};
int i, j, weektotal, total = 0;
double meanval;
printf("Week Mean hit\n");
printf("-------------\n");
for(i = 0; i < WEEK; i++) {
weektotal = 0;
for(j = 0; j < DAY; j++) {
weektotal += a[i][j];
total += a[i][j];
}
meanval = (double)weektotal/DAY;
printf(" %d%10.2f\n", i+1, meanval);
}
return 0;
}
此当前代码计算5行中每一行的均值。
答案 0 :(得分:0)
您可以使用与行所做的几乎相同的方式执行此操作。只需改变循环的顺序和更多的东西。
#include <stdio.h>
#define WEEK 5
#define DAY 7
int main(void) {
/* or int a[][DAY] = {{367, 654, 545, 556, 565, 526, 437}, */
int a[WEEK][DAY] = {{367, 654, 545, 556, 565, 526, 437},
{389, 689, 554, 526, 625, 537, 468},
{429, 644, 586, 626, 652, 546, 493},
{449, 689, 597, 679, 696, 568, 522},
{489, 729, 627, 729, 737, 598, 552}};
int i, j, daytotal, total = 0;
double meanval;
printf("Day Mean hit\n");
printf("-------------\n");
for(j = 0; j < DAY; j++) {
daytotal = 0;
for(i = 0; i < WEEK; i++) {
daytotal += a[i][j];
total += a[i][j];
}
meanval = (double)daytotal/WEEK;
printf(" %d%10.2f\n", j+1, meanval);
}
return 0;
}