我正在尝试将我的总和存储到一个变量中,以将这些年之间的百分比相加。现在,我对如何执行此操作感到困惑。我搜索了答案并尝试了一些方法,但是还没有运气。我想知道是否有人可以向我指出正确的方向来解决这个问题。我一直在获取内存位置而不是值。我是一名大学生,所以请多多包涵。任何帮助将不胜感激。这是我要检查的代码。
#define years 4
#define months 12
int main(void)
{
float percentage [4];
int i = 0, j = 0, n = 0, sum = 0;
int time[] = { 2012,2013,2014,2015};
int *value[years];
const char* name[]= {" JAN ", "FEB ", "MAR ", "APR ", "MAY ", "JUN ", "JUL ","AUG ","SEP ","OCT ","NOV ","DEC "};
int range[years][months] = {
{ 5626, 5629, 5626, 5606, 5622, 5633, 5647, 5656, 5673, 5682, 5728, 5728},
{ 5741, 5793, 5814, 5811, 5831, 5854, 5857, 5874, 5900, 5923, 5954, 5939},
{ 5999, 6020, 6062, 6103, 6115, 6128, 6169, 6194, 6219, 6233, 6256, 6301},
{ 6351, 6378, 6371, 6409, 6426, 6426, 6437, 6441, 6451, 6484, 6549, 6597}
};
printf(" YEAR %s %s %s %s %s %s %s %s %s %s %s %s\n", name[0], name[1], name[2], name[3], name[4], name[5], name[6],name[7],name[8],name[9],name[10],name[11]);
/* for(n=0; n < name; n++)
printf("%s", name[n]); // code keeps crashing my program
*/
for (i = 0; i < years; i++) {
printf(" %i ", time[i]);
for (j = 0; j < months; j++)
printf("%2i ", range[i][j]);
printf("\n");
}
for (i = 0; i < years; i++) {
for(j = 0, sum = 0; j < months; j++)
sum += range[i][j];
printf("\n This is the sum of months for %i: %i", time[i], sum);
}
for (i = 0; i < years; i++) {
for(j = 0, sum = 0; j < months; j++)
value[years] = sum;
printf("\n%i", value);
}
return 0;
}
更改value
为的数组int
。使其value
成为指针数组没有任何意义。
int value[years]; // Drop the *
您可以使用以下框来计算每年的总和。
for (i = 0; i < years; i++) {
for(j = 0, sum = 0; j < months; j++)
sum += range[i][j];
printf("\n This is the sum of months for %i: %i", time[i], sum);
}
但是,总和不会被存储。每年都会被覆盖。
您需要做的是将总和保存在中value
。用:
for (i = 0; i < years; i++)
{
value[i] = 0;
for(j = 0, sum = 0; j < months; j++)
{
value[i] += range[i][j];
}
printf("\n This is the sum of months for %i: %i", time[i], value[i]);
}
之后,您根本不需要最后一个循环。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句