如何计算具有指数的字符串 [英] How to evaluate string that have exponential
问题描述
Javax ScriptEngine和JEval的工作原理相似,您输入一个字符串并发送给它进行求值,它将返回结果:
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:
在ScriptEngine中(几乎在Jeval中相同):
In ScriptEngine (almost the same in JEval):
System.out.println(engine.eval("2*3+4"));
将导致:
10.0
但是当我尝试使其呈指数级时:
But when I try to make it an exponential:
System.out.println(engine.eval("2^3+4"));
将导致:
5.0
但这确实应该导致12(2 ^ 3 = 8 ,8 + 4 = 12),所以我的问题是,如何将其设置为将成为整个方程的字符串,评估支持指数并正确得出结果?
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?
我应该使用其他库吗?
推荐答案
^
是XOR操作数,您的字符串表示 2 XOR 3 + 4
,实际上它的计算结果为 1 + 4
。
^
is the XOR operand, your string means 2 XOR 3 + 4
, which in facts evaluates to 1 + 4
.
您必须使用
Math.pow(2,3) + 4
这是我的代码:
System.out.println(engine.eval("Math.pow(2,3) + 4"));
输出:
12.0
这篇关于如何计算具有指数的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!