用Python3.6实现计算器的基本功能,如:+,-,*,/,^等。
解决问题的参考资料:
要注意的是:输入含有括号“()”,小数点 “.”,以及使用内置的float类型会导致计算结果不够精确的问题。
基本思路是:使用逆波兰表达式算法。
代码实现:
from decimal import Decimal
#将输入转化成一个列表
string = input()
args=list(string)
#多位数被按位拆成了多个元素存在列表中,将它们重新整合成一个元素
length =len(args)
i=1
while(i<length):
if(args[i-1]=='(' or args[i-1]==')' or args[i-1]=='+' or args[i-1]=='-' or args[i-1]=='*' or args[i-1]=='/' or args[i-1]=='^'):
i+=1
continue
if(args[i]!='(' and args[i]!=')' and args[i]!='+' and args[i]!='-' and args[i]!='*' and args[i]!='/' and args[i]!='^'):
args[i-1]+=args[i]
del args[i]
length-=1
i-=1
#碰到小数点,说明附近几个元素可以整合成一个小数
if args[i]=='.':
x=args.index('.')
args[x-1]+=args[x]
args[x-1]+=args[x+1]
del args[x]
del args[x]
i+=1
#将原列表转化成逆波兰表达式列表
pri={'(':0,')':0, '+':1,'-':1, '*':2,'/':2,'^':3}
stack1=[]
stack2=[]
for x in args:
if(x=='('):
stack1.append(x)
elif(x==')'):
top=stack1.pop()
while(top!='('):
stack2.append(top)
top=stack1.pop()
elif(x=='+' or x=='-' or x=='*' or x=='/' or x=='^'):
if(len(stack1)==0):
stack1.append(x)
else:
top1=stack1.pop()
if(pri[x]>pri[top1]):
stack1.append(top1)
stack1.append(x)
else:
while(1):
if(pri[x]>pri[top1]):
stack1.append(top1)
break
stack2.append(top1)
if(len(stack1)==0):
break
top1=stack1.pop()
stack1.append(x)
else:
stack2.append(x)
while(len(stack1)!=0):
stack2.append(stack1.pop())
nibolan=[]
stack=[]
while(len(stack2)!=0):
nibolan.append(stack2.pop())
#进行数学计算
while(1):
top=nibolan.pop()
if(top=='+' or top=='-' or top=='*' or top=='/' or top=='^'):
y=Decimal(stack.pop())
x=Decimal(stack.pop())
if(top=='+'):
stack.append(x+y)
if(top=='-'):
stack.append(x-y)
if(top=='*'):
stack.append(x*y)
if(top=='/'):
stack.append(x/y)
if(top=='^'):
stack.append(x**y)
while(len(stack)!=0):
nibolan.append(stack.pop())
else:
stack.append(top)
if(len(nibolan)==0):
break
print(stack[0])
解决问题的参考资料:
1.逆波兰表达式算法的介绍:点击打开链接
2.decimal模块的介绍:点击打开链接
本文介绍了使用Python3.6实现计算器的基本功能,特别提到在处理括号、小数点和浮点数精度问题时,可以采用逆波兰表达式算法,并提供了相关模块decimal的介绍链接。
1109

被折叠的 条评论
为什么被折叠?



