Magic Square 2D阵列

时间:2016-11-17 03:44:06

标签: c arrays pointers multidimensional-array fopen

我的任务是创建一个C程序,它将读取.txt文件,将其转换为2D数组,并测试它是否是魔方(意味着所有列,行和对角线加起来为{ {1}},其中n是行,列或对角线中的整数.txt文件包含3个4x4正方形,3组16个,最后一个数字为零。所以神奇的总和是34.我得到了要添加的行,但我似乎无法弄清楚列或对角线。另外,我觉得我的代码现在的方式,它只会读取一次文件,并且无法读取其他两个4x4套。这是我的代码(对不起,现在它非常草率。我已经和它摔跤了一段时间,所以它有点乱)

[n(n^2 + 1)] / 2)

谢谢,非常感谢任何帮助

以下是int main (){ int array1[4][4], array2[4][4], array3[4][4], number=1, row, col, diag;//I messed with adding new arrays to send to functions, but it doesn't really do anything FILE *file1; file1 = fopen ("testdata.txt", "r"); if(file1!=NULL){ printf(" Square Perfect?\n----------------------------\n"); row=testRows(file1, array1, number); col=testCols(file1, array3, number); number++; } else printf("File could not be read.\n"); return 0; } int testRows (FILE *file1, int array1[4][4], int number){ int i, j=0, r=0, q, tru=9000, array2[4][4], input; if (file1!=NULL){ for(q=0; q<4; q++){ j=0; r=0; for (i=0; i<4; i++){ fscanf(file1, "%d", &array1[i][j]); r=r+array1[i][j];//sum of rows } j++; if (r!=34){ tru=0; break; } if (r==34){ tru=1; } } } return tru; } int testCols(FILE *file1, int array1[4][4], int num){ //this is the problematic function int i, j=0, r=0, q, tru=9000, array2[4][4], input; if(num==1){//ignore this file1 = fopen("testdata.txt", "r");//Before I added this, this function would read the next 16 numbers in the file and read their rows, when I need them to read the first 16 and their columns. I feel like this will really hurt when I need the function to read further into the file. Any suggestions? } if (file1!=NULL){ for(j=0; j<4; j++){ r=0; for(i=0; i<4; i++){ fscanf(file1, "%d", &array1[i][j]); printf("%d ", array1[i][j]); r+=array1[i][j];// sum printf(" ~%d~ ", r); //this is so I can see what the sum currently is. For some reason, it will only add up rows and not columns. } printf("\n"); } //^^^^^ I have moved i's and j's around all over the place, but no matter what, it will print and add the sum of each row. } // return tru; variable tru is to return to main whether or not the square is magic; have not gotten that far yet. } /*int testDiag(){ } */

testdata.txt

UPDATE! 我重新编写整个程序,现在完美运行。看看:

1 15 14 4 10 11 8 5 7  6  9  12  16  2  3  13 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 

1  3  4  5  6  7  12  8  9  15  7  9  4  3  12  13  

0 

0 个答案:

没有答案