Search code examples
objective-cioscs193p

Assignment 1 of CS193p


I recently started following the online course on iPhone development from Stanford University on iTunes U.

I'm trying to do the homework assignments now for the first couple of lectures. I followed through the walkthrough where I built a basic calculator, but now I'm trying the first assignment and I can't seem to work it out. Having some issues:

Trying to implement these:

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.

My code for performOperation is this:

-(double)performOperation:(NSString *)operation
{
    double result = 0;
    double result1 = 0;
    if ([operation isEqualToString:@"+"]){
        result = [self popOperand] + [self popOperand];
    }else if ([@"*" isEqualToString:operation]){
        result = [self popOperand] * [self popOperand];
    }
    else if ([@"/" isEqualToString:operation]){
        result = [self popOperand] / [self popOperand];
    }
    else if ([@"-" isEqualToString:operation]){
        result = [self popOperand] - [self popOperand];
    }
    else if ([@"C" isEqualToString:operation])
    {
        [self.operandStack removeAllObjects];
        result = 0;
    }
    else if ([@"sin" isEqualToString:operation])
    {
       result1 = [self popOperand];
        result = sin(result1); 
    }
    else if ([@"cos" isEqualToString:operation])
    {
        result1 = [self popOperand];
        result = cos(result1);
    }
    else if ([@"sqrt" isEqualToString:operation])
    {
        result1 = [self popOperand];
        result = sqrt(result1);
    }

    [self pushOperand:result];
    return result;
}

Facing some problems such as :

  1. i get inf when i type 5 enter 3 /
  2. also not sure whether my code for sin,cos and sprt are correct?

Solution

  • There is one error in your division.

    If you type now '2 enter 4 enter /', you will get 2 (4/2) as answer. It should be 0.5 (2/4).

    Maybe this hint helps.

    You could shorten your functions to 'result = sin([self popOperand]);' for instance.

    Anyway when you are stuck try to use NSLog() and print interesting values in the console. Is really useful when debugging.