尝试从
.dad
文件读取以下矩阵时
1 3 −3 1
−1 3 2 0
2 4 0 7
程序奇怪地只读取前两个值:
PS C:\Users\...\P1> gcc -o main_gauss main_gauss.c linalg.c
PS C:\Users\...\P1> ./main_gauss.exe
Matrix A:
1.000000 3.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000
它始终如一地执行此操作,即无论矩阵如何,它都只读取前两个值。如果相关的话,我正在使用 Visual Studio Code。
main_gauss.c
:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "linalg.h"
int main(void){
int n = 3;
int m = 4;
/* Allocate memory for matrix A */
double **A = (double **) malloc(n * sizeof(double *)); // Allocate memory for rows
for (int i = 0; i < n; i++) {
A[i] = (double *) malloc(m * sizeof(double)); // Allocate memory for columns
}
read_matrix(n, m, A, "Gauss1.dad");
return 0;
}
linalg.c
:
#include "linalg.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void read_matrix(int n, int m, double **A, char *s){
/* Open the file */
FILE * file ;
file = fopen (s, "r");
if ( file == NULL ){
printf("Error opening %s\n", ".dad file.");
return;
}
/* Import data to A */
printf("\nMatrix A:\n");
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
fscanf(file, "%lf", &A[i][j]);
printf("%lf ", A[i][j]);
}
printf("\n");
}
printf ("\n");
fclose(file); // Close the file
}
lingalg.h
:
#ifndef LINALG_H
#define LINALG_H
void read_matrix(int n, int m, double **A, char *s);
#endif
数据中有减号,Unicode 字符 8722。
%lf
的 fscanf
转换期望连字符代表减号。编辑 Gauss1.dad
文件将减号更改为连字符。或者编辑代码来读取字符(作为字符串或单个字符,而不是使用 %lf
)并解析减号。