Objective C 中的命令行计算器

Command Line Calculator in Objective C

我想在 C/Objective C 中实现一个命令行应用程序,它将充当多于两个数字的计算器。

例如./calc 5 + 4 * 6 = 29

我只需要一个想法或简单的算法即可开始。我将不胜感激。

您想要的算法是中缀表示法到后缀表示法转换器。 您可以在此处找到更多相关信息。

http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm.

编辑: 我不确定这是否有帮助,但这是 Java 中的一个实现。我不熟悉 Objective-C

    // converts a infix string to postfix string
private void convertInfixToPostfix(){
    // create an empty operand stack
    operatorStack = new Stack<>();
    Operator operator = null;
    Operand operand = null;
    for(int i = 0; i < expressionTokens.size(); i++){
        String token = expressionTokens.get(i);
        Element element = new Element(token);

        if(element.isOperand(token)){ // check if element is operand
            // add the element to the postfix string
            operand = new Operand(element.getStringValue());
            postFixString.add(operand);
        }
        else if(operatorStack.isEmpty()){ 
            // push the token to the operator stack, its an operator
            operator = new Operator(element.getStringValue());
            operatorStack.push(operator);
        }
        else {
            operator = new Operator(element.getStringValue());
            while(!operatorStack.isEmpty() && 
                    (operatorStack.peek().getPrecedence() 
                    <= operator.getPrecedence()))    
                postFixString.add(operatorStack.pop());

            operatorStack.push(operator);
        }
    }

    // add the rest of the operator stack to the postfix string
    while(!operatorStack.isEmpty()){
        Operator remainingOperator = operatorStack.pop();
        postFixString.add(remainingOperator);
    }
}