如何从字符串中提取方程式并对其求解,然后将答案放回 javascript 中的字符串中?
How do I take an equation from a string and solve it then put the answer back into a string in javascript?
所以我有一个变量,我们称之为等式。在这种情况下,这是一个表示“5+10”的字符串。如何编写一些代码来解决这个问题,然后将其放回字符串中打印回给用户?
这可能有帮助
function Calculate(){
var n1 = document.getElementById("n1").value
var n2 = document.getElementById("n2").value
var op = document.getElementById("op").value
var ans = document.getElementById("ans")
switch(op){
case '+':
ans.value = parseFloat(n1) + parseFloat(n2);
break;
case '-':
ans.value = parseFloat(n1) - parseFloat(n2);
break;
case '*':
ans.value = parseFloat(n1) * parseFloat(n2);
break;
case '/':
ans.value = parseFloat(n1) / parseFloat(n2);
break;
default:
ans.value = "Invalid Operator";
break;
}
}
<p><input type="number" id="n1" style="text-align:center;" placeholder="Enter 1st Number" minimum="0" value="0" oninput="Calculate()" >
<input type="string" max-length="1" id="op" size="5px" style="text-align:center;" placeholder="Operator" oninput="Calculate()">
<input type="number" id="n2" oninput="Calculate()" placeholder="Enter 2nd Number" minimum="0" value="0" style="text-align:center;" ></p>
<input type="disabled" id="ans" placeholder="Answer" style="text-align:center;" >
所以我有一个变量,我们称之为等式。在这种情况下,这是一个表示“5+10”的字符串。如何编写一些代码来解决这个问题,然后将其放回字符串中打印回给用户?
这可能有帮助
function Calculate(){
var n1 = document.getElementById("n1").value
var n2 = document.getElementById("n2").value
var op = document.getElementById("op").value
var ans = document.getElementById("ans")
switch(op){
case '+':
ans.value = parseFloat(n1) + parseFloat(n2);
break;
case '-':
ans.value = parseFloat(n1) - parseFloat(n2);
break;
case '*':
ans.value = parseFloat(n1) * parseFloat(n2);
break;
case '/':
ans.value = parseFloat(n1) / parseFloat(n2);
break;
default:
ans.value = "Invalid Operator";
break;
}
}
<p><input type="number" id="n1" style="text-align:center;" placeholder="Enter 1st Number" minimum="0" value="0" oninput="Calculate()" >
<input type="string" max-length="1" id="op" size="5px" style="text-align:center;" placeholder="Operator" oninput="Calculate()">
<input type="number" id="n2" oninput="Calculate()" placeholder="Enter 2nd Number" minimum="0" value="0" style="text-align:center;" ></p>
<input type="disabled" id="ans" placeholder="Answer" style="text-align:center;" >