【问题标题】:how do you store data from a for loop into a variable for other calculations?如何将 for 循环中的数据存储到变量中以进行其他计算?
【发布时间】:2016-06-14 04:49:54
【问题描述】:

我正在尝试将我的总和存储到一个变量中,以在年份之间加起来一个百分比。现在我很困惑如何做到这一点。我搜索了答案并尝试了一些东西,但还没有运气。我想知道是否有人能指出我正确的方向来解决这个问题。我一直在获取内存位置而不是值。我是大学生,请多多包涵。任何帮助将不胜感激。这是我要查看的代码。

#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;

}

【问题讨论】:

  • 在最后一个 for 循环中,您将 sum 设置为 0 并且从不更改它。所以你最终将所有值设置为 0。
  • 同样在最后一个循环中,您忘记使用 [years] 括号和索引,以便打印该索引处的值。
  • 感谢您的回复。我现在来看看。
  • 我不清楚你在问什么。但是,注释掉的循环的问题在于您将nname 进行比较,这没有任何意义,因为name 是一个数组。将测试更改为 n &lt; months 以修复该循环。
  • 更多问题供您查看。 value[years]=sum 是缓冲区溢出,因为years 不是有效索引(最大有效索引为years-1)。 int *value[years] 声明了一个指针数组,但随后您尝试存储 int 值。也许你的意思是int value[years];

标签: c arrays pointers for-loop


【解决方案1】:

value 更改为ints 的数组。将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]);
}

在那之后,您根本不需要最后一个循环。

【讨论】:

  • 非常感谢。我真的很感激。
  • @RTriplett,不客气。我很高兴能够提供帮助。
猜你喜欢
  • 2021-11-09
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
相关资源
最近更新 更多