user2388026
user2388026

Reputation: 165

Solving a Variable Equation defined by the User

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.

Upvotes: 11

Views: 1108

Answers (3)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158529

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.

Upvotes: 17

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215387

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

Upvotes: 0

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

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.

Upvotes: 1

Related Questions