2014-04-06 2 views
1

저는 매년 그리드를 인쇄하는 c 프로그램을 작성하려고합니다. for 루프는 iterates가 인자로 선택한 몇 년 동안 매년 그리드를 출력합니다. for 루프는 웬일인지 그 위에 놓인 경계를 초과하는 무한 수의 기간 동안 모눈을 인쇄합니다.for 루프는 C로 끝나지 않습니다

int main(int argc, char *argv[]) { 
if (argc != 3) /* argc should be 2 for correct execution */ 
{ 
    /* We print argv[0] assuming it is the program name */ 
    printf("usage: %s filename", argv[0]); 
} else { 
    int year = atoi(argv[1]); 
    double gridA[11][11]; 
    double gridB[11][11]; 
    int in; 
    int n; 
    printf("%d\n",year); 
    FILE *file = fopen(argv[2], "r"); 
    for (int i = 0; i < 12; i++) { 
     fscanf(file, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", 
       &gridA[i][0], &gridA[i][1], &gridA[i][2], &gridA[i][3], 
       &gridA[i][4], &gridA[i][5], &gridA[i][6], &gridA[i][7], 
       &gridA[i][8], &gridA[i][9], &gridA[i][10], &gridA[i][11]); 
    } 
    fclose(file); 
    for(n = 0; n < year; n++) { 
     printf("Year %d: \n", n); 
     if (n == 0) { 
      for (int i = 0; i < 12; i++) { 
       for (int j = 0; j < 12; j++) { 
        if (j == 11) { 
         printf("%.1lf\n", gridA[i][j]); 
        } else { 
         printf("%.1lf ", gridA[i][j]); 
        } 
       } 
      } 
     } else if (n % 2) { 
      in = nextDependency(gridA, gridB); 
      for (int i = 0; i < 12; i++) { 
       for (int j = 0; j < 12; j++) { 
        if (j == 11) { 
         printf("%.1lf\n", gridB[i][j]); 
        } else { 
         printf("%.1lf ", gridB[i][j]); 
        } 
       } 
      } 
     } else { 
      in = nextDependency(gridB, gridA); 
      for (int i = 0; i < 12; i++) { 
       for (int j = 0; j < 12; j++) { 
        if (j == 11) { 
         printf("%.1lf\n", gridA[i][j]); 
        } else { 
         printf("%.1lf ", gridA[i][j]); 
        } 
       } 
      } 
     } 
    } 
} 
exit(0); 
} 

(가) 끝나지 않아 루프이 하나입니다 : 다음은 코드의

FILE *file = fopen(argv[2], "r"); 
    for (int i = 0; i < 12; i++) { 
     fscanf(file, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", 
       &gridA[i][0], &gridA[i][1], &gridA[i][2], &gridA[i][3], 
       &gridA[i][4], &gridA[i][5], &gridA[i][6], &gridA[i][7], 
       &gridA[i][8], &gridA[i][9], &gridA[i][10], &gridA[i][11]); 
    } 
: 내가 루프 때이 코드 앞에 유한 한 것으로 나타났습니다

for(n = 0; n < year; n++) { 
printf("Year %d: \n", n); ... 

디버깅 시도를 통해

하지만 그 코드를 넣으면 무한 루프가됩니다. 왜 이런 일이 일어나는지 알 수없는 버그입니까? 아무도 내가 이것을 고칠 수있는 아이디어가 있습니까?

답변

5

크기가 11 x 11 인 격자를 정의했지만 12 개의 요소를 읽었습니다. 마지막 요소는 루프 변수를 덮어 씁니다.

일반적으로 크기가 n 인 배열을 정의하면 0에서 n-1까지 요소에 액세스 할 수 있습니다.

이 경우 솔루션은 모든 12 개의 요소에 대해 공간이있는 격자를 정의하는 것입니다.

관련 문제