我想在C / Objective C中实现一个命令行应用程序,它将作为两个以上数字的计算器。
例如/ calc 5 + 4 * 6 = 29
我只需要一个想法或简单的算法即可开始。我将不胜感激任何帮助。
答案 0 :(得分:2)
您想要的算法是后缀表示法转换器的中缀表示法。 你可以在这里找到更多信息。
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);
}
}