Solving a Variable Equation defined by the User

2019-03-13 14:34发布

问题:

Answers in C, Python, C++ or Javascript would be very much appreciated. I've read a few books, done all the examples. Now I'd like to write a simple program. But, I already ran into the following roadblock:

My intention is to take an equation from the user and save it in a variable, For example:

-3*X+4 or pow(2,(sin(cos(x))/5))       >  [In valid C Math syntax]

And then calculate the given expression for a certain X-Value. Something like this:

printf("%g", UserFunction(3.2))   // Input 3.2 for X in User's Function and Print Result

Any ideas? For the life of me, I can't figure this out. Adding to my frustration, the solution is likely a very simply one. Thank you in advance.

回答1:

There isn't a simple way to do this in C but I think muParser may be useful to you, it is written in C++ but has C binding. ExprTk is also an option but looks like it is C++ only, on the plus side it looks much easier to get interesting results with.

Another option may be the Expression Evaluation which is part of Libav. It is in C and the eval.h header has some good descriptions of the interface.



回答2:

In compiled languages like C, C++, or Java there is no easy way to do this--you basically have to rewrite a whole compiler (or use an external library with an interpreter). This is only trivial in "scripting" languages like Python and Javascript, which have a function (often called "eval()") that evaluates expressions at runtime. This function is often dangerous, because it can also do things like call functions with side effects.



回答3:

Ffmpeg/libav has a nice simple function evaluator you could use.