0

我正在从一个简单的数据文件“matrix.dat”中读取数据,例如:

1 2 3
4 5 6
7 8 9

我通读文件并将数据点保存在二维数组中:

else /// Read data from file.
{
    // Check matrix is square and find number of columns/rows.
    n = CheckSquare(matrixData); /// n = dimension of square matrix
    fprintf(stdout, "n = %d\n", n); /// TESTING ///

    if(n != 0) /// Matrix is square.
    {
        int i, j; /// i = rows, j = columns.
        double MATRIX[n - 1][n - 1]; /// Declare 2D array of size n x n.

        // Loop through file "matrix.dat" and store data into 2D array "MATRIX".
        for(i = 0; i < n; i++) /// Loop rows.
        {
            for(j = 0; j < n; j++) /// Loop columns.
            {
                fscanf(matrixData, "%lf", &MATRIX[i][j]); /// Store data point as matrix element.
                fprintf(stdout, "[%d][%d] = %lf\n", i, j, MATRIX[i][j]); ///TESTING ///
            }
        }

        // Calculate the determinant of matrix "MATRIX".
        ///det = Determinant(n, MATRIX); /// COMMENT OUT ///
        ///fprintf(stdout, "Determinant = %lf\n", det); /// COMMENT OUT ///
        for(i = 0; i < n; i++) /// Loop rows.
        {
            for(j = 0; j < n; j++) /// Loop columns.
            {
                fprintf(stdout, "[%d][%d] = %lf\n", i, j, MATRIX[i][j]);
            }
        }
    }

你可以看到我为了测试目的打印了两次矩阵。有一次我正在读取文件并存储数据,然后在初始 for 循环完成后再次。

他们应该打印出完全相同的东西,因为我没有对两个 for 循环之间的 2D 数组“MATRIX”进行任何操作。

然而,这是打印出来的(当使用上面的'matrix.dat'文件时):

n = 3
[0][0] = 1.000000
[0][1] = 2.000000
[0][2] = 3.000000
[1][0] = 4.000000
[1][1] = 5.000000
[1][2] = 6.000000
[2][0] = 7.000000
[2][1] = 8.000000
[2][2] = 9.000000

[0][0] = 1.000000
[0][1] = 2.000000
[0][2] = 4.000000
[1][0] = 4.000000
[1][1] = 5.000000
[1][2] = 5.000000
[2][0] = 5.000000
[2][1] = 8.000000
[2][2] = 9.000000

任何帮助将不胜感激。

以防万一,这是“CheckSquare”功能:

// Checks if matrix is square and returns the dimension if TRUE.
// Otherwise returns 0.
int CheckSquare(FILE* m)
{
    int dim; /// Dimension of matrix.
    int dataNum = 0; /// Holds number of data points in file "matrixData".
    double temp; /// Temporary variable to hold double data.

    // Check matrix is square and find number of columns/rows.
    while(fscanf(m, "%lf", &temp) != EOF) /// Data can still be read from file "matrixData".
    {
        dataNum++; /// Adds to number of data points.
    }
    rewind(m); /// Sets the position indicator to the beginning of the file "matrixData".

    dim = sqrt(dataNum); /// Number of columns and rows if 'dataNum' is perfect square.

    if(dim*dim == dataNum) /// Matrix is square.
    {
        return(dim);
    }

    else
    {
        return(0);
    }
}
4

1 回答 1

2

如果 n 为 3,则有效索引为 0,1,2,但您要像这样声明矩阵:

double MATRIX[n - 1][n - 1];

但应该这样声明:

double MATRIX[n][n];

如果您使用这样的循环:

for(i = 0; i < n; i++) /// Loop rows.
{
    for(j = 0; j < n; j++) /// Loop columns.
    {

当 n == 3 时,它遍历 0、1 和 2。

于 2013-11-05T19:09:10.583 回答