[英]Is there a way to show the step by step computation of a calculation in Java?
I am currently building an Android app that has a calculator that not only shows the result, but also shows how it reached that result? 我目前正在构建一个具有计算器的Android应用程序,该计算器不仅可以显示结果,还可以显示如何达到该结果?
Is there any library or any way that I could show a step by step computation for the result of the code below? 是否有任何库或任何方式可以显示下面代码的逐步结果?
int a = 5;
int b = 6
int c = 7;
int d = 8;
int result = a + (b * c) / d;
edit: By the way, it's a calculator for physics so I have lots of formulas. 编辑:顺便说一下,这是一个物理计算器,所以我有很多公式。 I'm using exp4j to parse a string formula as an expression. 我正在使用exp4j将字符串公式解析为表达式。 Here's a sample 这是一个样本
//For formula velocity = (finalVelocity - initialVelocity) / time
String formula1 = "(finalVelocity - initialVelocity) / time";
Double result1 = new ExpressionBuilder(formula)
.variables("finalVelocity", "initialVelocity", "time")
.build()
.setVariable("finalVelocity", 4);
.setVariable("initialVelocity", 2);
.setVariable("time", 2)
.evaluate();
//Sample Output
//velocity = (4 - 2) / 2
//velocity = 2 /2
//velocity = 1
//For formula finalVelocity = (velocity * time) + initialVelocity
String formula2 = "(velocity * time) + initialVelocity";
Double result12 = new ExpressionBuilder(formula)
.variables("velocity", "time" "initialVelocity")
.build()
.setVariable("velocity", 4);
.setVariable("time", 2)
.setVariable("initialVelocity", 0)
.evaluate();
//Sample Output
//finalVelocity = (4 * 2) + 0
//finalVelocity = 8 + 0
//finalVelocity = 8
With many formulas, I'm trying to eliminate printing each step per formula. 对于许多公式,我试图消除打印每个公式的每个步骤。 I'm trying to find a way to have a function that would print the steps for any formula. 我正在尝试找到一种方法来打印任何公式的步骤。
Considering you will be using BODMAS to solve that problem, you could consider simply printing each step: 考虑到您将使用BODMAS解决该问题,可以考虑简单地打印每个步骤:
int a = 5;
int b = 6;
int c = 7;
int d = 8;
int ans = (b * c);
System.out.println(ans)
ans /= d;
System.out.println(ans)
ans += a;
System.out.println(ans)
To do this, you can build a function which searches for brackets first and solves the equations in the according to BODMAS(Brackets first, then Division, then Multiplication, then Addition, and finally Subtraction) . 为此,您可以构建一个函数,该函数首先搜索方括号,然后根据BODMAS求解方程式(先是方括号,然后是除法,然后是乘法,然后是加法,最后是减法) 。
Considering you take the equation as a string, you first search for (), then solve /
and print answers followed by *
, +
and -
. 考虑将方程式作为字符串,您首先搜索(),然后求解/
并打印答案,后跟*
, +
和-
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.