gpt4 book ai didi

c - 如何获得线性方程的系数

转载 作者:太空狗 更新时间:2023-10-29 15:42:27 25 4
gpt4 key购买 nike

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

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

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

带有系数的矩阵将是:

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

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

规则:

The equations of the system need to be LINEAR, otherwise the program will be closed.

If the coefficient and the variable of the equation doesn't exist, the coefficient is 0.

If the coefficient doesn't exist, but the variable exists, (x, y, z for example), the coefficient is 1.

The variable can be any letter, it doesn't need to be x, y and 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;
}

最佳答案

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

关于c - 如何获得线性方程的系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52664490/

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