【问题标题】:How to Get the Coefficients Of A Linear Equation如何获得线性方程的系数
【发布时间】:2018-10-05 11:20:33
【问题描述】:

在这个程序中,我需要得到一个线性系统,这个系统有n个变量和n 方程。我需要在文本文件(.txt)中提取方程的系数并将它们放在矩阵上。文本文件的第一行有一个number,即系统中方程的个数。其他行有 方程式

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

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;
}

【问题讨论】:

  • 您需要详细说明您的问题并展示您的尝试。简短回答:自己解析每一行文本并提取系数。这应该不会太难。 scanf 不会做这项工作。
  • 你需要写一个解析器。在编写解析器之前,您需要准确定义要解析的内容的预期格式。
  • 第一行的'3'有什么意义?
  • 4 案例中的符号是什么?
  • 变量可以是任意字母,这是另一个问题

标签: c coefficients


【解决方案1】:

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

【讨论】:

  • 这是个好主意,但是如何提取这些现有系数?你刚才说的用 if 和 else 就完成了
  • 你需要改变你的问题,恰恰相反(+1代表+,-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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2021-01-09
    • 2015-11-12
    • 2015-05-08
    • 2019-11-06
    • 2015-01-13
    • 2022-01-23
    相关资源
    最近更新 更多