输入一个表达式字符串,计算其结果
输入格式:
行1:输入字符串数目
下面分别输入要计算的表达式
输出格式:
输出计算结果,结果保留2位小数。对于异常数据能输出相应异常信息。
实现
我的实现为仅针对两位操作数计算,如果需要多位操作数并且判断操作符,可以参考 中/后缀表达式进行实现。
我的另一篇文章:C语言中缀表达式求值(综合)
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File : test_1.py
@Contact : lking@lking.icu
@Author : Jason
@Date : 4/1/2022 1:35 PM
@Description Python version-3.10
"""
def op(params, ch):
"""
@param params: number list
@param ch: operation char
@return: None.
"""
try:
result = eval(f"{params[0]}{ch}{params[1]}")
print(f"{result:0.2f}")
except NameError as e:
print("NameError")
except ZeroDivisionError as e:
print("ZeroDivisionError")
except SyntaxError as e:
print("SyntaxError")
def fun(ls):
"""
@param ls: string list
@return: None
"""
for s in ls:
if '+' in s:
s = s.split('+')
op(s, '+')
if '-' in s:
s = s.split('-')
op(s, '-')
if '*' in s:
s = s.split('*')
op(s, '*')
if '/' in s:
s = s.split('/')
op(s, '/')
def question():
"""
only operation two number formula and function's relation is worse than meta function.
@return:
"""
ls = []
n = int(input())
while n > 0:
ls.append(input())
n -= 1
fun(ls)
if __name__ == "__main__":
question()
输出
3
1+2
3/2
a+1
3.00
1.50
NameError
Q.E.D.