简体   繁体   English

电源输入 javascript 评估 function

[英]Power in javascript eval function

I am using Javascript engine in java to calculate the value of the math expression that I insert as a String.我在 java 中使用 Javascript 引擎来计算我作为字符串插入的数学表达式的值。 Here is the code:这是代码:

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String infix = "(2^2+5*2+3)%13";
    Double F = (Double) engine.eval(infix);
    int f = F.intValue();
    System.out.println(f);`

However, it gives me 0, and the correct solution would be 4. I understand this is because of the ^, because when I tried to write the expression like this "(2*2+5*2+3)%13", I got the correct result.但是,它给了我 0,正确的解决方案是 4。我知道这是因为 ^,因为当我尝试编写这样的表达式“(2*2+5*2+3)%13”时,我得到了正确的结果。 So, my question is how to get power of a number using javascript eval?所以,我的问题是如何使用 javascript eval 获取数字的幂?

When using powr you need to use the ** operator instead of ^ :使用powr时,您需要使用**运算符而不是^

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String infix = "(2**2+5*2+3)%13";
Double F = (Double) engine.eval(infix);
int f = F.intValue();
System.out.println(f);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM