当加减乘除一起存在时,写出正确运算的代码
时间: 2024-03-11 18:50:35 浏览: 22
好的,下面是一个简单的 Python 代码示例,可以处理加减乘除四则运算:
```python
# 定义一个计算器函数,输入参数为字符串类型的数学表达式
def calculator(expression):
# 将字符串表达式转换为列表,方便处理
expression_list = list(expression)
# 定义一个空列表,用于存放数字和运算符
element_list = []
# 定义一个变量,记录当前数字的值
current_num = 0
# 遍历字符串表达式中的每个字符
for i in expression_list:
# 如果当前字符是数字,累加到 current_num 中
if i.isdigit():
current_num = current_num * 10 + int(i)
# 如果当前字符是运算符,将当前数字和运算符作为一个元素存入 element_list 中
elif i in ['+', '-', '*', '/']:
element_list.append(current_num)
element_list.append(i)
current_num = 0
# 将最后一个数字加入 element_list 中
element_list.append(current_num)
# 定义一个栈,用于存放数字和运算符
stack = []
# 遍历 element_list 中的每个元素
for i in element_list:
# 如果当前元素是运算符,从栈中取出前两个数字进行运算,并将结果压入栈中
if i in ['+', '-', '*', '/']:
num2 = stack.pop()
num1 = stack.pop()
if i == '+':
result = num1 + num2
elif i == '-':
result = num1 - num2
elif i == '*':
result = num1 * num2
elif i == '/':
result = num1 / num2
stack.append(result)
# 如果当前元素是数字,直接压入栈中
else:
stack.append(i)
# 栈中最后一个元素即为表达式的运算结果
return stack.pop()
```
这个计算器函数可以处理四则运算,例如:
```python
>>> calculator('2+3*4-6/2')
11.0
```
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)