我正在尝试将我的金额存储到一个变量中,以便在这些年之间累加一个百分比。现在我很难过如何做到这一点。我搜索了答案并尝试了一些事情,但还没有运气。我想知道是否有人能指出我正确的方向来解决这个问题。我不断获取内存位置,而不是价值。我是大学生,所以请耐心等待。任何帮助将不胜感激。这是我要审核的代码。
#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;
}
答案 0 :(得分:1)
将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]);
}
之后,根本不需要最后一个循环。