简体   繁体   English

将线性方程的系数从文件读入 c 中的二维数组

[英]Read coefficients of linear equations from file into 2d array in c

I'm working on a program that reads linear equations from a file such as those - and solve them using matrices - :我正在开发一个程序,该程序从诸如这些文件中读取线性方程 - 并使用矩阵求解它们 - :

3x+2y-2z=9
-2x+9y+12z=23
4x-7y+9z=45

The file is supposed to contain n equations with n variables , how to get only the numbers and the signs from the above equations to store in 2d dynamic array of Integers该文件应该包含具有 n 个变量的 n 个方程,如何仅从上述方程中获取数字和符号以存储在 2d 整数动态数组中

So output will be (some thing like this):所以输出将是(类似这样的事情):

 3  2 -2  9
-2  9 12 23
 4 -7  9 45

Thanks in Advanced提前致谢

Using fscanf , the 'd' modifier handles signed integer, that means it will take care of the input number whether it has + or - in front of it, try following code:使用fscanf , 'd' 修饰符处理有符号整数,这意味着它会处理输入数字前面是否有+- ,请尝试以下代码:

#include <stdio.h>

int main(void) {
    int x, y, z, e;
    FILE *fp = fopen("eq.txt", "r");
    if (!fp)
        return 1;
    while (fscanf(fp, "%dx%dy%dz=%d", &x, &y, &z, &e) == 4) {
        printf("%d %d %d %d\n", x, y, z, e);
    }
    return 0;
}

It outputs for the file you posted:它为您发布的文件输出:

3 2 -2 9
-2 9 12 23
4 -7 9 45

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM