smus Posted October 27, 2018 Share Posted October 27, 2018 Elements of an array of a math formula look like this: a = [1,'+',2,'-',3,'*',4,'/',5]; How do I perform all the arythmetic actions between those numbers. The array elements may be different, because they are added dynamically. It would not be difficult if I didn't have to prioritize the actions (/,*,_,-). I tried using splice() method, but something goes wrong. Maybe I can somehow sort the elements according to the math actions priority? Link to comment Share on other sites More sharing options...
Ingolme Posted October 27, 2018 Share Posted October 27, 2018 It's not simple, it requires a bit of thinking and work. The first step is to convert the current array to postfix notation. Once you're in a postfix notation, the algorithm to perform the calculation is simple. Link to comment Share on other sites More sharing options...
smus Posted October 30, 2018 Author Share Posted October 30, 2018 (edited) eval() works in this case, but I am not sure what the right priority is (operator precedence) in Javascript. Some websites has info that divistion(/) has the highest priority then goes multiplication, addition and subtraction. That is strange, because usually multiplication is the first. 1-2+3*4/5 = 1.4 according to JS compliler (/ then * then - then +, no idea why it counts like that) 1-2+3*4/5 = 1.6 according to Windows Calc (I guess, it counts without any priority) 1-2+3*4/5 = -3.4 if we use the correct operator precedence (* / + -) What I was taught in high school is that the correct precedence must be: * / + - Never thought that there might be another order in programming languages. Edited October 30, 2018 by smus Link to comment Share on other sites More sharing options...
Ingolme Posted October 30, 2018 Share Posted October 30, 2018 Multiplication and division have the same precedence, addition and subtraction have the same precedence. When two operators of the same precedence are found, the leftmost operation is done first. Link to comment Share on other sites More sharing options...
smus Posted October 31, 2018 Author Share Posted October 31, 2018 13 hours ago, Ingolme said: Multiplication and division have the same precedence, addition and subtraction have the same precedence. When two operators of the same precedence are found, the leftmost operation is done first. Exactly, right. The precedence goes pair(* and /) over pair(+ and -) and the Win Calc must be set to a kind of formula mode to use precedence order, otherwise it counts numbers from left to right as they are. Thanks! Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now