高精度简易计算器
编程思路:
1、导入Decimal,精度设置为小数点后100位。
2、把输入的计算表达式(字符串)按列表形式保存。
3、判断列表中的数字s,把数字用Decimal(s)进行替代。
4、再把替换后的列表转换成字符串。
5、采用exec函数执行字符串表达式。
6、获取高精度的计算结果(精确到小数点后100位,可以设置小数点后任意位)。
from decimal import *
import copy
getcontext().prec = 100 # 计算精度设置
base_data = list('.0123456789')
add = list('Decimal(\'')
point = 0
string = ''
x = Decimal('0')
try:
string = str(input("请输入计算表达式(只包含9876543210.+-*/()):"))
temp = eval(string)
string1 = list(copy.deepcopy(string)) # 把字符串转换成列表,string1为原始列表,保持不变
string2 = list(copy.deepcopy(string)) # string2为需要替换的列表,使用point即时跟踪变化情况
length = len(string1)
for index, s in enumerate(string1):
if s in base_data: # 是数字的情况
if index == 0: # 首位时
for i in range(9): # 插入Decimal('
string2.insert(i + point + index, add[i])
point += 9
if string1[index + 1] not in base_data:
string2.insert(index + point + 1, '\')') # 后面插入')
point += 1
elif index == length - 1: # 末位时
if string1[index-1] not in base_data: # 如果末尾是一个独立的数字
for i in range(9):
string2.insert(i + point + index, add[i])
string2.append('\')')
else:
if string1[index - 1] in base_data and string1[index + 1] not in base_data: # 前面是数字,后面不是数字
string2.insert(index + point + 1, '\')')
point += 1
if string1[index - 1] not in base_data: # 前面不是数字
for i in range(9): # 前面插入Decimal('
string2.insert(i + point + index, add[i])
point += 9
if string1[index + 1] not in base_data: # 后面不是数字
string2.insert(index + point + 1, '\')')
point += 1
s = ''.join(string2) # 把列表再转换成字符串
exec("x=" + s) # 执行字符串表达式
print(x) # 如果未出差错,输出结果
except:
print("输入错误!")
D:\Python\study\venv\Scripts\python.exe D:/Python/study/20200811/高精度简易计算器.py
请输入计算表达式(只包含9876543210.+-*/()):1+2-3*4/5+(123/456+23*12.67)/712
1.009662551744529863985807214665878178592548787699586043761088113542282672974571259609698403311649911
Process finished with exit code 0