Solving a Variable Equation defined by the User

给你一囗甜甜゛ 提交于 2019-12-04 08:38:39

问题


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.



来源:https://stackoverflow.com/questions/16577756/solving-a-variable-equation-defined-by-the-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!