I’m working on a ‘Equation Calculator’ but have a few problems. I can now insert my equation but I want it to be numbers, but not just numbers: I want all the ‘+’ ‘s, the ‘-‘ ‘s, the ‘*’ ‘s and the ‘/’ ‘s to be the right things.
So here is my code until now:
var ligning = prompt("Insert your equation here:");
var newLigning = ligning.split("=");
var sideOne = parseInt(newLigning[0],10);
var sideTwo = parseInt(newLigning[1],10);
var calculator = function() {
};
alert(sideOne);
alert(sideTwo);
To be very specific here is an example:
‘1 + 2 = 3’ should alert 3 and then 3 again (because of the two alerts down in the bottom) – How can I make that?
Instead of :
You might want to have something of the sort :
Where :
performMathcould be done in a few ways. You need to split the equation and obtain the numbers and the equations between the 2. This can be done recursively!I think this could be a good starting point.
Edit
Unraleted to the question, if you start taking the operation priority (PEDMAS) into account this is a slightly harder task. The approach is the same,
performMathwould need to be slightly more complexe. In such a case, I would recomend some sort of array structure for the numbers and another for the equations.Edit 2
Paul SAlso made a good point of sanitising the string before getting started. You cannot assume someone will enter an equation. When programming Rich Cook said:Edit 3
This little snippet of code should be somewhat helpful… by all means this might not the most efficient code…
Now all you have to do is go through the arrays and perform the proper operations.