gpt4 book ai didi

c - 将文件中的数字读入二维矩阵

转载 作者:行者123 更新时间:2023-11-30 20:04:58 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来将文件中的数字读取到二维矩阵中; mm_alloc() 函数是一个创建空矩阵的函数,并且该文件的第一行是矩阵的大小;但代码似乎无法从文件中读取,我的问题是什么?我是否错误地使用了 fgets()sscanf()

double **mm_alloc( int size )
{
double **matrix;
int i;
matrix = (double **)malloc((size) * sizeof(double *));
for ( i = 0; i < size; i++ ) {
matrix[i] = (double *)malloc(size);
}
return( matrix );
}


double **mm_read( char *filename, int *size )
{
FILE *myfile;
myfile = fopen(filename, "r");
char read[256];
fgets(read, 256, myfile);
sscanf(read, "%d", size);
int i, j;
double **Matrix;
Matrix = mm_alloc( *size );
for ( i = 0; i < *size; i++ ) {
for ( j = 0; j < *size; j++) {
fgets(read, 256, myfile);
sscanf(read, "%lf", &Matrix[i][j]);
}
}
fclose (myfile);
return( Matrix );
}

void mm_free( int size, double **matrix )
{
int i;
for ( i = 0; i < size; i++ ) {
free(matrix[i]);
}
free(matrix);
}

void mm_print( int size, double **matrix )
{
int i, j;
for ( i = 0; i < size; i++ ) {
for ( j = 0; j < size; j++ ) {
printf("%16f", matrix[i][j]);
}
printf("\n");
}
}

double **mm_swap( int size, double **matrix )
{
double **swap;
swap = mm_alloc(size);
int i, j;
for ( i = 0; i < size; i++ ) {
for ( j = 0; j < (size-2); j++) {
swap[i][j] = matrix[i][j+2];
swap[i][j+2] = matrix[i][j];
}
}
return( swap );
}

double **mm_matrix_mult( int size, double **matrix, double **transpose )
{
double **matrix_mult;
matrix_mult = mm_alloc(size);
int i, j, k;
double result;
for ( i = 0; i < size; i++ ) {
for ( j = 0; j < size; j++ ) {
result = 0;
for ( k = 0; k < size; k++ ) {
result += (matrix[i][k] * transpose[k][j]);
}
matrix_mult[i][j] = result;
}
}
return( matrix_mult );
}

int main()
{
char filename[256];
double **matrix=NULL;
double **swap_matrix=NULL;
double **results_matrix=NULL;
int size=0;

printf("Please enter the matrix data file name: ");
scanf( "%s", filename );

matrix = mm_read( filename, &size );
swap_matrix = mm_swap( size, matrix );
results_matrix = mm_matrix_mult( size, matrix, swap_matrix );

mm_print( size, results_matrix );
mm_free( size, matrix );
mm_free( size, swap_matrix );
mm_free( size, results_matrix );
return( 0 );
}

文件内容:

4
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
10.0
11.0
12.0
13.0
14.0
15.0
16.0

最佳答案

您正在使用“w”打开文件。

这将删除该文件。您需要使用“r”打开才能读取文件。

关于c - 将文件中的数字读入二维矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35220533/

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