键盘输入三个整数和两个算术运算组成的表达式,计算结果。 运算符包括:加+,减-乘*,除/ 输入格式: 三个整数,两个运算符,组成算数表达式,输入的字符之间没有空格 输出格式: 在表达式的后边输出=计算结果
时间: 2024-12-09 08:16:19 浏览: 12
为了实现这个功能,你可以编写一个简单的程序,例如用 Python 编程,通过字符串处理解析输入的表达式,然后按照优先级计算结果。这里有一个基本的例子:
```python
def calculate_expression(expression):
# 定义运算符优先级
priority = {"+": 1, "-": 1, "*": 2, "/": 2}
def apply_operator(operators, values):
operator = operators.pop()
right = values.pop()
left = values.pop()
if operator == "+":
values.append(left + right)
elif operator == "-":
values.append(left - right)
elif operator == "*":
values.append(left * right)
elif operator == "/":
try:
values.append(left / right)
except ZeroDivisionError:
print(f"Error: Division by zero not allowed")
return None
operands = []
operators = []
for token in expression:
if token.isdigit():
operands.append(int(token))
elif token in priority:
while (operators and priority[token] <= priority[operators[-1]]):
apply_operator(operators, operands)
operators.append(token)
elif token == ")":
while operators[-1] != "(":
apply_operator(operators, operands)
operators.pop()
# 处理剩余的运算符和操作数
while operators:
apply_operator(operators, operands)
# 返回最终结果
return operands[0] if len(operands) == 1 else "Invalid expression"
# 示例输入
expression = input("请输入一个表达式 (e.g., 5+3*2): ")
result = calculate_expression(expression)
if result is not None:
print(f"{expression} = {result}")
阅读全文