如何获得线性方程的系数

时间:2018-10-05 11:20:33

标签: c coefficients

在此程序中,我需要获取线性系统解决方案,并且该系统具有 n 个变量和 n < / strong>方程式。我需要在文本文件(.txt)中提取方程式的系数,并将其放在矩阵上。文本文件的第一行具有 number ,即系统中的 equations 数。其他行,有等式

例如,如果我有以下文本文件:

3
2x - 3y = 0
4x + z = 12
5y - 6z = 10

系数矩阵为:

|2 -3  0  0|
|4  0  1 12|
|0  5 -6 10|

我知道如何获得线性系统的解,但是我如何仅获得系统的系数(没有库)?我尝试了仅从字符串(char的向量)中读取数字的函数,但是如果系数是字母(返回0)或不存在,则它们将不起作用。

规则:

  

系统方程式必须为 LINEAR ,否则程序将关闭。

     

如果方程式的系数和变量不存在,则系数为0。

     

如果系数不存在,但变量存在(例如x,y,z),则系数为1。

     

变量可以是任何字母,不必是x,y和z。

代码:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAXCHAR 1000
#include "LinkedList.c"

//in the future use STRTOK e SSCANF (SPRINTF maybe)

int main() {
FILE *fp;
char str[MAXCHAR];
int character;
int c = 0;
char fileaddress[50];
char *cp;
char *variaveis;
char *p;

int quant = 0;
int numDeEquacoes = 0;

printf("Enter the address of the file you want to open: ");

gets(fileaddress);
printf(fileaddress);


//int coeficientes[3][3];

fp = fopen(fileaddress, "r");
if (fp == NULL){
    printf("\n");
    printf("Cannot open file %s",fileaddress);
    return 1;
}
    printf("\n");

while (fgets(str, MAXCHAR, fp) != NULL)
{
    quant++;

    if(quant==1)
    {
        numDeEquacoes = (str[0] - '0');
    }

    printf("%s", str);

    //gets(str, sizeof(str), stdin);
        printf("Variables of equation: ");

        for(cp=str; *cp; ++cp)
            if(isalpha(*cp))
            {
               printf("%c", *cp, "\n");
               //scanf("%c", )
            }

            //THE CODE THAT RESULTS IN ONLY NUMBERS
            while (*p)
            {
                if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1))) )
                {
                    long val = strtol(p, &p, 10); 
                    printf("%ld\n Coefficients:", val, "\n");
                }
                else
                {
                    p++;
                }
            }//ENDS HERE


        //printf("Variaveis: ", variaveis);
        //printf("\n");

    //variaveis = strstr(str);
    //printf(variaveis);


}

fclose(fp);

if(quant-1!=numDeEquacoes)
{
    printf("The number of equations is wrong!\n");
    printf("The number of equations is: %i", numDeEquacoes,"\n");
    printf("The variable quant is: %i", quant,"\n");

    return 0;
}

//int coeficientes[numDeEquacoes][numDeEquacoes];

//printf("coef:",coeficientes);

return 0;
}

2 个答案:

答案 0 :(得分:0)

您应该读取信号(+或-)并乘以系数。如果信号为+,则乘以+1,否则乘以-1。如果没有变量(或字母),则系数为0。

答案 1 :(得分:-2)

我现在没有时间用C编写代码,但是我有这种python方法,因为如果您想检查算法的话。我得到的输出是

[[2, -3, 0, 0],
 [4, 0, 1, 12],
 [0, 5, -6, 10]]

您必须检查是否有符号(+或-)(假设+),获取数字(如果不存在则为1)并存储字母(变量)。然后在每个符号(+,-或=)和空格处重新启动该过程。

对于矩阵,启动一个列计数器和一个用于列索引的数组,然后每次在数组中找到用于索引的变量搜索(如果不存在),则将该计数器分配为该列的列索引变量并增加它。

代码在这里:

# - For reading the coefficients:
# 3
# 2x - 3y = 0
# 4x + z = 12
# 5y - 6z = 10

def get_index(d, c):
    if c in d.keys():
        return d[c] 
    else:
        return -1
s=1 #sign
n_fg = 0 #number exist
eq_fg = 0 #equal flag
s_fg = 0 #sign flag
letter = '' # store current letter (variable)
coef =''
curr_idx = 0

N = int(input())

letter_idx = {}

mat = [[0 for i in range(N+1)] for i in range(N)]

for i in range(N):

    l = input()
    coef = ''
    eq_fg = 0
    s_fg = 0
    s = 1
    ls = len(l)
    k = 0 # position in line str

    for c in l:

        if c == '-':
            s_fg = 1
            s=-1
        elif c == '+':
            s_fg = 1
            s = 1
        elif c.isalpha():
            if n_fg == 0:
                coef = 1
            letter = c
        elif c.isdigit():
            n_fg = 1
            coef += c

            if k == ls-1:
                if coef is '':
                    coef = 1
                coef = s*int(coef)
                if eq_fg == 0:
                    j = get_index(letter_idx,letter)
                    if j == -1:
                        j = curr_idx
                        letter_idx[letter] = j
                        curr_idx+=1
                else:
                    j = N
                mat[i][j] = coef

        elif (c == ' ' and s_fg != 1) :
            if coef is '':
                coef = 1
            coef = s*int(coef)
            if eq_fg == 0:
                j = get_index(letter_idx,letter)
                if j == -1:
                    j = curr_idx
                    letter_idx[letter] = j
                    curr_idx+=1
            else:
                j = N
            mat[i][j] = coef
            coef = ''
            n_fg = 0
        elif c == ' ' and s_fg == 1:
            s_fg = 0
        elif c == '=':
            eq_fg = 1
            s_fg = 1
            s = 1
        k+=1

print(mat)