【发布时间】: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