20194318 2020-2021-2 《Python程序设计》实验二报告
# 20194318 2020-2021-2 《Python程序设计》实验二报告
课程:《Python程序设计》
班级: 1943
姓名: 黄璟彤
学号:20194318
实验教师:王志强
实验日期:2021年4月27日
必修/选修: 公选课
## 1.实验内容
-
设计并完成一个完整的应用程序,完成加减乘除模等运算,功能多多益善。
- 考核基本语法、判定语句、循环语句、逻辑运算等知识点
## 2. 实验过程及结果
对于这一实验我设计的计算器是将中序计算式转化为后序计算式之后进行计算,这样用户在输入的时候可以直接输入自己想要计算的算式
不需要将数据和计算符分别输入
经过编写这一程序可以进行加减乘除模,以及求次方的运算
实验代码如下:
import math
num = []
other = []
n = 0
f=0
a = input("想要计算的算式: ")
for k in a:
if k.isdigit():
num.append(k)
n += 1
else:
if(k=='('):
n=0
f=1
other.append(k)
if(k==')'):
n=2
poped_other=other.pop()
while poped_other!='(':
if poped_other!='(':
num.append(poped_other)
poped_other=other.pop()
continue
if(n==1):
other.append(k)
if(n==2):
n -= 1
if(k=='-' or k=='+'):
poped_other=other.pop()
num.append(poped_other)
while poped_other!='(' and len(other)!=0:
if len(other)!=0:
poped_other=other.pop()
if poped_other!='(':
num.append(poped_other)
if poped_other=='(':
other.append(poped_other)
other.append(k)
if(k=='/' or k=='*' or k=='%'):
poped_other=other.pop()
if(poped_other=='+' or poped_other=='-'):
other.append(poped_other)
if(poped_other=='/' or poped_other=='*' or poped_other=='%' or poped_other=='^'):
num.append(poped_other)
other.append(k)
if(k=='^'):
poped_other=other.pop()
if(poped_other!='^'):
other.append(poped_other)
else:
num.append(poped_other)
other.append(k)
while len(other)!=0:
popend_other=other.pop()
num.append(popend_other)
print('转换为后序计算式:',num)
n=0
while len(num)!=0 or len(other)!=1:
if n!=2:
pop_num=num.pop()
other.append(pop_num)
if pop_num.isdigit():
n += 1
continue
else:
n = 0
if(n==2):
a=int(other.pop())
b=int(other.pop())
c=other.pop()
if(len(other)>0):
d=other.pop()
if type(d)==int or type(d)==float or d.isdigit():
n=1
else:
n=0
other.append(d)
if c=='-':
re=a-b
other.append(re)
if c=='+':
re=a+b
other.append(re)
if c=='/':
re=a/b
other.append(re)
if c=='*':
re=a*b
other.append(re)
if c=='%':
re=a%b
other.append(re)
if c=='^':
re=math.pow(a,b)
other.append(re)
n += 1
continue
print('计算结果为:',other)
实验结果截图如下:
## 3. 实验过程中遇到的问题和解决过程
- 问题1:怎么将中序计算式转换为后序计算式
- 问题1解决方案:通过翻阅数据结果的教科书学习解决思路,再进行代码的编写
- 问题2:在转换过程中对于加入列表的数据顺序有点困难,尤其是在加入括号之后对于数据的读取
- 问题2解决方案:查找数据出错的位置,调整代码语句,反复实验进行多次调整
## 其他(感悟、思考等)
python与C语言的语法结构还是有许多差异,在编写python代码时还是会不自觉的用C语言的思路去考虑