DEV Community

maxazillion
maxazillion

Posted on

Calculator

One of the more difficult problems that I assigned myself in my limited time as a programer was to make a calculator. Even after I decided to put the project down it wasn't in a perfectly working state. It would be nice to come back the the problem and bulletproof my code later on. The calculator was deceptively hard to build.

I chose to only use the base operations that were built into the programing language (-*/+) so the main issue I faced was to program order of operations. I would expect the user to put in a string as an input "7/5 (6 + 7)" and give them a number as an output.

The first part of the order of operations was to take the lowest level of parens. This was difficult because It was hard to determine what the lowest level was. I came up with a system where I counted open parens "(" and closed parens ")." when my open parens matched the amount of closed parens I would cut that string out and out it in a struct array.

I can't remember off the top of my head If I decided to make a tree or assign a value to the struct for level of importance. I'm pretty sure I made a tree I'm not going to go over my code because I don't want to spoil the fun when I try to recreate it. Anyways, I'm pretty sure I made a tree of structs and the lower you got on the tree the higher the priority of the order of operations was.

The code would do something like this...
ex "7 + 4 (6-5 (4+2))"
top of tree : "7 + 4 operation x"
second branch : "6 - 5 operation x"
third branch : "4 + 2"

The struct would keep an operation as a placeholder that would default to multiplication unless otherwise stated. It would also hold an area of where the branch underneath the current branch would go in its string. Once the math is resolved which would at this point just be standard pemdas without the "p" and the "e", I would send the number value of that branch up for the rest of the problem to be resolved. This would go on until the problem is solved. I'm sure that this isn't the best way to solve this problem and there are likely a few bugs here and there. If you're new give it a shot, it took me like a whole month to figure it out. If you're experienced it probably could be solved in a sitting, don't give me your answers until I have a new perfectly functioning calculator built. Thanks

Top comments (0)