It is necessary to implement a program for solving equations on pure SI . Initially, to enter the equation itself implemented the following:

printf("Введите коэффициенты a, b и c"); scanf("%lf%lf%lf", &a, &b, &c); 

I would like to make it so that the user can enter a string, for example, 4x ^ 2-6x-2 = 0 , and the program distributes 4 , -6, and -2 among variables a , b, and c, respectively.

PS Is it possible to implement the following program? A person enters an equation of different types (square, cubic, fourth degree), and the program understands what type it is and distributes the coefficients.

1 answer 1

The code on the pluses (and certainly incorrect), but the idea does not change from this - we define the allowable sets of simvods and transitions between them, from which we dance further

 enum TokenType {NONE, DOT, DIGIT, OPERATOR, VARIABLE}; struct Token { TokenType type; string value; Token(type t, char v) { this.type = t; this.value = string(v); } }; TokenType tokenType(char chr) { if (chr >= '0' && chr <= '9') return DIGIT; if (chr >= 'a' && chr <= 'z') return VARIABLE; if (chr >= 'A' && chr <= 'Z') return VARIABLE; if (chr == '.') return DOT; } vector<Token> tokenize(string src) { vector<Token> tokens; TokenType old = NONE; char* c_src = src.c_str(); while (*c_src) { TokenType type = tokenType(c_src); if ( (old == NONE) && (type == DIGIT || type == VARIABLE || type == OPERATOR)) { tokens.push(Token(type, *c_src)); } else if (old == VARIABLE && (type == VARIABLE || type == DIGIT)) { tokens[tokens.size()-1].value += c_src; } else if (old == DIGIT && (type == DIGIT || type == DOT)) { tokens[tokens.size()-1].value += c_src; } else if (old == DIGIT && (type == VARIABLE || type == OPERATOR)) { tokens.push(Token(type, *c_src)); } else if (old == VARIABLE && (type == OPERATOR)) { tokens.push(Token(type, *c_src)); } else if (old == OPERATOR && (type == OPERATOR)) { tokens[tokens.size()-1].value += c_src; } else if (old == OPERATOR && (type == VARIABLE || type == DIGIT)) { tokens.push(Token(type, *c_src)); } c_src++; } return tokens; } 
  • The fact is that the pros do not know absolutely. And the algorithm is not very clear. Can you chew on a bit? - Ivan
  • I see here only lexical analysis. And syntax is also required ... - Mike
  • According to the algorithm - as correctly noted, this is a part. Those. there is a division into separate tokens: [4, x, ^, 2, -, 6, x, -2]. But further - depending on the task (and the form in which the equations are given). It can be divided by separators +/- ([[4, x, ^, 2], -, [6, x], -, [2]]). Well, I think - further work will not cause questions - Alexander Pozharskii