我最近开始在iTunes U上学习斯坦福大学关于iPhone开发的在线 class 。

我现在正在做前几节课的作业。我逐步完成了构建基本计算器的演练,但是现在我正在尝试第一个任务,但似乎无法解决。有一些问题:

尝试实现这些:

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.

我的performOperation代码是这样的:
-(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;
}

面临一些问题,例如:
  • 输入5时我得到信息输入3 /
  • 还不确定我的sin,cos和sprt代码是否正确?
  • 最佳答案

    您的部门有一个错误。

    如果现在输入“2 enter 4 enter /”,您将得到2(4/2)作为答案。它应该是0.5(2/4)。

    也许这个提示会有所帮助。

    您可以将函数缩短为“结果= sin([self popOperand]);”。例如。

    无论如何,当您陷入困境时,请尝试使用NSLog()并在控制台中打印有趣的值。在调试时真的很有用。

    关于objective-c - CS193p的作业1,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9138395/

    10-13 04:05