This is not a good approach on many levels. First, just adding an operation to the "end" of a number (whatever you mean by "end" here) does not get you to order-of-operation. You need to keep track of the entire expression (or at least more than just the last operand). Since you're working in ObjC, you'll probably want an object-oriented approach to manage your expressions. Google for "object oriented calculator." There are many examples. (Do not worry whether the example is in ObjC; you should be able to apply the same object model in any OOP language.) @trojanfoe offers the beginnings of this, but getting to correct order-of-operation is more complicated. Luckily, it's been solved many times. See DDMathParser for one ObjC solution.
The next thing that's going to bite you is that double
is a dangerous type for a calculator. Your user expects to work in Base-10. double
works in Base-2. There are going to be rounding errors, and you wind up with results like 4.999999999 when you clearly meant 5. If you intend to display decimal, then work in decimal. Cocoa offers the NSDecimalNumber
class for this, as well as the NSDecimal
Foundation type.