【问题标题】:2D array working inside the loop but not working outside the loop二维数组在循环内工作但不在循环外工作
【发布时间】:2018-12-20 08:22:28
【问题描述】:

我编写了一个公式来读取 txt 文件,将其存储在数组(1D)中,然后读取数组以计算移动平均值(2D)。程序要求用户输入两个值(k1 & k2)并计算从k1k2 的每个值的移动平均值(基本上是找出最佳值) 以下是代码

#include<stdlib.h>
#define MAX_FILE_NAME 100
#define MAXCHAR 1000
int main()
{
  FILE *fp;
  int count = 0,k1=0,k2=0,k=0; // Line counter (result)
  int buy[k2][count],sell[k2][count];

  char filename[MAX_FILE_NAME];
  char c; // To store a character read from file

  // Get file name from user. The file should be
  // either in current folder or complete path should be provided
  printf("Enter file name or full path: ");
  scanf("%s", filename);
  printf("Enter the minimum rolling period for calculation : \n");
  scanf("%d", &k1);
  printf("Enter the maximum rolling period for calculation : \n");
  scanf("%d", &k2);
  // Open the file

  fp = fopen(filename, "r");

  // Check if file exists
  if (fp == NULL)
  {
    printf("Could not open file %s", filename);
    return 0;
  }

  // Extract characters from file and store in character c
  for (c = getc(fp); c != EOF; c = getc(fp))
    if (c == '\n') // Increment count if this character is newline
      count = count + 1;

  // Close the file
  fclose(fp);
  //printf("The file %s has %d lines\n", filename, count);

  FILE *myFile;
  myFile = fopen(filename, "r");

  //read file into array
  float numberArray[count];
  int i;

  if (myFile == NULL){
    printf("Error Reading File\n");
    exit (0);
  }
  for (i = 0; i < count; i++){
    fscanf(myFile, "%f,", &numberArray[i]);
  }

  fclose(myFile);

  for (k=k1;k<=k2;k++)
  {
    float n;
    float data[count],mag[k2][count];
    double avg,sum;
    for (i=0;i<k-1;i++)
    {
      mag[k][i-1]=0;
      sum=sum+numberArray[i];
    }

    for(i=k-1;i<=count;i++)
    {
      mag[k][i-1]=avg;
      sum=sum+numberArray[i]-numberArray[i-k];
      avg = sum/k;
    }

    //    for(i=0;i<=count;i++)
    //    {
    //        printf("MA[%d][%d] = %0.2lf     ",k,i,mag[k][i]);
    //        if (i%3==0)
    //            printf("\n");
    //    }
  }

  for(k=k1;k<=k2;k++)
  {
    for(i=0;i<=count;i++)
      printf("MA[%d][%d] = %0.2lf     ",k,i,mag[k][i]);
  }
}
}

现在,当我尝试在 for 循环之外打印 mag[k][i] 值时,它显示错误“mag”未声明。但是当我将打印命令放入循环中时(代码中的注释部分),它工作正常。

以下评论后更新的代码(仍然无法正常工作)

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>

#define MAX_FILE_NAME 100
#define MAXCHAR 1000

int main()
{
  FILE *fp;
  int count,k1,k2,k; // Line counter (result)
  char filename[MAX_FILE_NAME];
  char c; // To store a character read from file

  // Get file name from user. The file should be
  // either in current folder or complete path should be provided
  printf("Enter file name or full path: ");
  scanf("%s", filename);

  printf("Enter the minimum rolling period for calculation : \n");
  scanf("%d", &k1);

  printf("Enter the maximum rolling period for calculation : \n");
  scanf("%d", &k2);

  // Open the file
  fp = fopen(filename, "r");
  // Check if file exists
  if (fp == NULL)
  {
    printf("Could not open file %s", filename);
    return 0;
  }

  // Extract characters from file and store in character c
  for (c = getc(fp); c != EOF; c = getc(fp))
    if (c == '\n') // Increment count if this character is newline
      count = count + 1;

  // Close the file
  fclose(fp);
  //printf("The file %s has %d lines\n", filename, count);

  /****************
    File opening and reading section
   *****************************************************/
  FILE *myFile;
  myFile = fopen(filename, "r");

  //read file into array
  float numberArray[count];
  int i;

  if (myFile == NULL){
    printf("Error Reading File\n");
    exit (0);
  }
  for (i = 0; i < count; i++){
    fscanf(myFile, "%f,", &numberArray[i] );
  }
  fclose(myFile);

  /***********************************************
   Calculation of Moving Average and storing it in array
   ******************************************/
  int buy[k2][count],sell[k2][count];
  float mag[k2][count];
  for (k=k1;k<=k2;k++)
  {
    float data[count];
    double avg,sum;
    for (i=1;i<k;i++)
    {
      mag[k][i-1]=0;
      sum=sum+numberArray[i];
    }

    for (i=k-1;i<=count;i++)
    {
      mag[k][i-1]=avg;
      sum=sum+numberArray[i]-numberArray[i-k];
      avg = sum/k;
    }

//    for(i=0;i<=count;i++)
//    {
//        printf("MA[%d][%d] = %0.2lf     ",k,i,mag[k][i]);
//        if (i%3==0)
//            printf("\n");
//    }
   }

   for (k=k1;k<=k2;k++)
   {
     for (i=0;i<=count;i++)
     {
       printf("MA[%d][%d] = %0.2lf     ",k,i,mag[k][i]);
     }
   }
}

【问题讨论】:

  • 欢迎来到 SO。您可以通过正确缩进来大大提高代码的可读性。这将吸引更多读者。
  • int buy[k2][count],sell[k2][count]; 在这一行 count 包含 0。这可能不是你想要的。
  • 您可能会更新您的问题以显示新代码。使用“编辑”按钮并将修改后的代码添加到旧代码下方。不鼓励删除旧代码,因为它会使所有 cmets 和答案无用。
  • mag[k][i-1]=0; 在那个循环中,k 运行到 &lt;=k2 太多了,i 从 0 开始,使得 i-1 有点太低了。
  • char c 必须是 int c 否则您可能无法正确检测到 EOF。

标签: c arrays multidimensional-array


【解决方案1】:

问题归结为:mag 的范围仅限于for 循环内部:

  for (k = k1; k <= k2; k++)
  {
    ...
    int mag[k2][count];
    ... 
  }

  // mag is out of scope here
  // therefore following line won't compile:

  printf("%d", mag[0][0]);

您需要在 for 循环之外声明 mag,例如:

  int mag[k2][count];      
  for (k = k1; k <= k2; k++)
  {
    ...
  }

  printf("%d", mag[0][0]);
  ...

注意:您的代码中还有其他问题,在 cmets 中提到。

【讨论】:

  • 如果我将它放在循环之外,那么它不会在编译中显示错误,但在运行时会显示错误:无法读取引用内存中的指令。单击“确定”终止程序。
  • @MohdNaved 这是因为您的代码中存在其他不相关的错误。阅读 Gerhardh 的第二条评论。
  • 哦,是的,我的错误.. 我刚刚按照 Gerhardh 的指导进行了纠正.. 现在它可以工作了,但是现在出现了一个新问题.. 它显示 mag[][] 的所有值都等于零:-(
  • @MohdNaved 这是一个非常不同的问题。这是学习如何使用调试器的绝佳机会。这是一项时间上的小额投资,很快就会得到回报。
  • 当用户应该只输入一个 k 值,而 mag 是一维的时,代码工作正常。但是当我修改代码让用户输入两个值 k1 和 k2 时。并转换将平均移动到二维,从那时起我就有麻烦了。
猜你喜欢
  • 2021-06-24
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
相关资源
最近更新 更多