一.项目PSP表格
|
PSP表格指标 |
预估耗时(分钟) |
实际耗时(分钟) |
|
预估项目花费时间 |
160 |
170 |
|
需求分析与思路解析 |
20 |
15 |
|
代码实现 |
60 |
70 |
|
代码测试 |
30 |
30 |
|
代码优化 |
20 |
25 |
|
写博客 |
30 |
20 |
二.设计实现过程
实现类:三个类(除主类)分别为封装函数一:整数求解函数:zsResult();封装函数二:真分数求解函数:zsResult();运算函数:result(s,n1,n2)
其中,zsResult()和zsResult()中都调用运算函数result(s,n1,n2)来进行四则运算,同时result(s,n1,n2)类还负责输出结果
其中,运用random库中的randint方法随机生成整数,用random.choice(['+','-','*','/']) 来实现符号的随机生成,使用max()min()函数防止生成小数
三、代码说明:
求解真分数:zsResult()
def result(s,n1,n2):
if s == '+':
print('{} + {} = {}'.format(n1,n2,n1 + n2))
elif s == '-':
print('{} - {} = {}'.format(n1,n2,n1 - n2))
elif s == '*':
print('{} * {} = {}'.format(n1,n2,n1 * n2))
elif s == '/':
if n2 == 0:
print('***除数不能为零***')
else:
print('{} / {} = {}'.format(n1,n2,n1 / n2))
else:
print('输入有误,请重新输入!')
求解整数:zsResult()
def zsResult():
qes = int(input())
for a in range(qes):
rsign = random.choice(['+','-','*','/'])
rnum1 = random.randint(0,100)
rnum2 = random.randint(0,100)
if rnum1 < rnum2:
rnum1 = max(rnum1, rnum2)
rnum2 = min(rnum1, rnum2)
result(rsign,rnum1,rnum2)
else:
result(rsign,rnum1,rnum2)
result(s,n1,n2)
def zfsResult():
qes = int(input())
for b in range(qes):
rsign = random.choice(['+','-','*','/'])
snum1 = random.randint(0,100)
mnum1 = random.randint(1,100)
zfs1 = Fraction(snum1, mnum1)
snum2 = random.randint(1,100)
mnum2 = random.randint(1,100)
zfs2 = Fraction(snum2, mnum2)
if zfs1 < zfs2:
zfs1 = max(zfs1, zfs2)
zfs2 = min(zfs1, zfs2)
result(rsign,zfs1,zfs2)
else:
result(rsign,zfs1,zfs2)
四、测试运行:


五、代码优化
鉴于原本的真分数运算中,算式中出现有假分数出现,故对负责假分数运算的函数进行修改
def zfsResult():
qesd = int(input())
for b in range(qesd):
rdsign = random.choice(['+','-','*','/'])
sdnum1 = random.randint(0,100)
mdnum1 = random.randint(1,100)
if sdnum1<mdnum1:
zfs1 = Fraction(sdnum1, mdnum1)
else:
zfs1 = Fraction(mdnum1, sdnum1)
sdnum2 = random.randint(1,100)
mdnum2 = random.randint(1,100)
if sdnum2<mdnum2:
zfs2 = Fraction(sdnum2, mdnum2)
else:
zfs2 = Fraction(mdnum2, sdnum2)
if zfs1 < zfs2:
zfs1 = max(zfs1, zfs2)
zfs2 = min(zfs1, zfs2)
result(rsign,zfs1,zfs2)
else:
result(rdsign,zfs1,zfs2)
测试结果如下

可以发现计算结果中仍旧有假分数,为了将假分数结果化成带分数,所以需要进一步的优化
我从两方面出发,一是将真分数和整数的运算函数分开,
#新增的真分数结果运算函数
def zfsResult(zfss,m1,m2): if zfss == '+': print('{} + {} = {}'.format(m1,m2,jhd(m1 + m2))) elif zfss == '-': print('{} - {} = {}'.format(m1,m2,jhd(m1 - m2))) elif zfss == '*': print('{} * {} = {}'.format(m1,m2,jhd(m1 * m2))) elif zfss == '/': if m2 == 0: print('***除数不能为零***') else: print('{} / {} = {}'.format(m1,m2,jhd(m1 / m2))) else: print('输入有误,请重新输入!')
二是增加一个将假分数运算结果转化成带分数的转化函数。
#假分数转化带分数
def jhd(f): a=f.numerator b=f.denominator if a%b==0: return '%d'%(a/b) elif a<b: return '%d%s%d' % (a,'/',b) else: c=int(a/b) a = a - c * b return '%d%s%d%s%d' % (c,'’',a,'/',b)
优化后测试结果如下

