用scala语言写一段中缀表达式求值的代码
时间: 2023-12-17 10:45:27 浏览: 73
中缀表达式求值
4星 · 用户满意度95%
以下是使用Scala语言编写的中缀表达式求值代码:
```scala
import scala.collection.mutable.Stack
def evaluateExpression(expression: String): Int = {
val operators = Stack[Char]()
val operands = Stack[Int]()
var i = 0
while (i < expression.length) {
val token = expression(i)
if (token.isDigit) {
var num = token.toString.toInt
while (i + 1 < expression.length && expression(i + 1).isDigit) {
num = num * 10 + expression(i + 1).toString.toInt
i += 1
}
operands.push(num)
} else if (token == '(') {
operators.push(token)
} else if (token == ')') {
while (operators.top != '(') {
val op = operators.pop()
val op2 = operands.pop()
val op1 = operands.pop()
operands.push(applyOperator(op, op1, op2))
}
operators.pop()
} else if (token == '+' || token == '-' || token == '*' || token == '/') {
while (operators.nonEmpty && hasPrecedence(token, operators.top)) {
val op = operators.pop()
val op2 = operands.pop()
val op1 = operands.pop()
operands.push(applyOperator(op, op1, op2))
}
operators.push(token)
}
i += 1
}
while (operators.nonEmpty) {
val op = operators.pop()
val op2 = operands.pop()
val op1 = operands.pop()
operands.push(applyOperator(op, op1, op2))
}
operands.pop()
}
def applyOperator(operator: Char, operand1: Int, operand2: Int): Int = {
operator match {
case '+' => operand1 + operand2
case '-' => operand1 - operand2
case '*' => operand1 * operand2
case '/' => operand1 / operand2
}
}
def hasPrecedence(op1: Char, op2: Char): Boolean = {
if (op2 == '(' || op2 == ')') false
else if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) false
else true
}
val expression = "((4+3)*2-1)/5"
val result = evaluateExpression(expression)
println(s"The result of $expression is $result")
```
此代码使用堆栈(Stack)数据结构来解析中缀表达式。它遍历表达式中的每个字符,并根据它是数字,运算符或括号来执行不同的操作。它还使用applyOperator和hasPrecedence函数来执行操作并确定运算符的优先级。最终,该函数返回表达式的计算结果。
阅读全文