小学四则运算编程实践
小学四则运算编程实践
参考博客链接:http://www.cnblogs.com/jiel/p/4810756.html、 https://www.cnblogs.com/saiwa/articles/5253713.html
import random
import math
import fractions
q = []
ans = []
#整数运算
def c1(q,ans):
symbol = random.choice(['+','-','×','÷']) #生成随机运算符号
if symbol == '+':
n1 = random.randint(0,10)
n2 = random.randint(0,10)
q.append(str(n1)+'+'+str(n2)+'=')
ans.append(n1 + n2)
elif symbol == '-':
n1 = random.randint(0,10)
n2 = random.randint(0,10)
n1,n2 = max(n1,n2),min(n1,n2) #保证被减数>减数
q.append(str(n1)+'-'+str(n2)+'=')
ans.append(n1 - n2)
elif symbol == '×':
n1 = random.randint(0,10)
n2 = random.randint(0,10)
q.append(str(n1)+'×'+str(n2)+'=')
ans.append(n1 * n2)
else:
n1 = random.randint(0,10)
if n1 == 0:
n2 = random.randint(1,10)
else:
n2 = random.randint(1,n1+1)
q.append(str(n1)+'÷'+str(n2)+'=')
ans.append(fractions.Fraction(n1,n2))
#输出
n=k=int(input("写出你需要多少道题:"))
print("题目已生成好,请去去文件里查看")
while n>0:
c1(q,ans)
n -= 1
f = open("Exercises.txt",'w')
g = open("Answers.txt",'w')
j = 0
while j<k:
question=q[j]
answer=str(ans[j])
x=j+1
f.write("第""%d""个问题:"%x)
f.write(question)
g.write(answer)
f.write('\n')
g.write('\n')
j += 1
f.close()
g.close()
#检查
print("完成作业并把答案写在Answer.txt里")
yes = input("如已完成,请输入\'yes':")
if yes == 'yes' or 'y' or 'Y':
q=open('Answer.txt')
g=open('Answers.txt')
x=list(q)
y=list(g)
o=0
C=0
v=[]
i=[]
while o<k:
if x[o]==y[o]:
C+=1
t=o+1
v.append(t)
else:
p=o+1
i.append(p)
o+=1
X=k-C
G=open('Grade.txt','w')
G.write('Correct:')
G.write(str(k))
G.write(str(v))
G.write('\n')
G.write('Wrong:')
G.write(str(k))
G.write(str(i))
G.close()
只是实现了初步的,有些并不符合要求,比如在我测试代码的时候会出现一些重复的题,以及会有假分数出现等等,目前正在查找解决方案。