How to evaluate string that have exponential

ぃ、小莉子 提交于 2019-12-31 03:55:11

问题


Javax ScriptEngine and JEval works similarly, you input an string and send it to be evaluated, and it will return you the result of it:

In ScriptEngine (almost the same in JEval):

System.out.println(engine.eval("2*3+4"));

will result in:

10.0

But when I try to make it an exponential:

System.out.println(engine.eval("2^3+4"));

will result in:

5.0

But it really should result in 12 (2^3 = 8, 8+4=12), so my question is how can I set it up in a way that the string which the will be all the whole equation, will evaluate supporting the exponential, and result correctly?

Should I use another library?


回答1:


^ is the XOR operand, your string means 2 XOR 3 + 4, which in facts evaluates to 1 + 4.

You have to use

Math.pow(2,3) + 4

This is my code:

System.out.println(engine.eval("Math.pow(2,3) + 4"));

Output:

12.0


来源:https://stackoverflow.com/questions/18836358/how-to-evaluate-string-that-have-exponential

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