gpt4 book ai didi

c - 二维数组在没有被操纵的情况下丢失值?

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:37 24 4
gpt4 key购买 nike

我正在从一个简单的数据文件“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]);
}
}
}

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

它们应该打印出与我在两个 for 循环之间未对二维数组“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);
}
}

最佳答案

如果 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。

关于c - 二维数组在没有被操纵的情况下丢失值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19796773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com