Please note, this blog entry is from a previous course. You might want to check out the current one.
Add the following 4 operation buttons:
- sin : calculates the sine of the top operand on the stack.
- cos : calculates the cosine of the top operand on the stack.
- sqrt : calculates the square root of the top operand on the stack.
- π: calculates (well, conjures up) the value of π. Examples: 3 π * should put three times the value of π into the display on your calculator, so should 3 Enter π *, so should π 3 *. Perhaps unexpectedly, π Enter 3 * + would result in 4 times π being shown. You should understand why this is the case. NOTE: This required task is to add π as an operation (an operation which takes no arguments off of the operand stack), not a new way of entering an operand into the display.
Add four additional buttons called “sin”, “cos”, “sqrt” and “pi” by copying one of the existing operator buttons and adjust the performOperation function in CalculatorBrain.m:
} else if ([operation isEqualToString:@"sin"]) result = sin([self popOperand]); else if ([operation isEqualToString:@"cos"]) result = cos([self popOperand]); else if ([operation isEqualToString:@"sqrt"]) { double number = [self popOperand]; if (number < 0) return 0; result = sqrt(number); } else if ([operation isEqualToString:@"π"]) result = M_PI;
The reason that “π Enter 3 * + would result in 4 times π” is that pushing the Enter button puts result “3.14” from the pi operation on the stack.