四则运算(python)
这个作业属于哪个课程 | < https://edu.cnblogs.com/campus/ahgc/AHPU-SE-19)> |
---|---|
这个作业要求在哪里 | https://edu.cnblogs.com/campus/ahgc/AHPU-SE-19/homework/11376 |
这个作业的目标 | <写一个能自动生成小学四则运算题目的程序> |
学号 | <3190704230> |
源代码: | |
import random | |
from fractions import Fraction |
整数的四则运算
def count1(question, ans1):
print("欢迎来到整数的四则运算")
print("加法(请选1)减法(请选2)乘法(请选3)**除法(请选4)")
p = int(input())
if p == 1:
#加法
n1 = random.randint(0, 20)
n2 = random.randint(0, 20)
question.append(str(n1) + '+' + str(n2) + '=')
ans1.append(n1 + n2)
elif p == 2:
#减法
n1 = random.randint(0, 20)
n2 = random.randint(0, 20)
n1,n2 = max(n1,n1),min(n1,n2)#保证出现的数字为正数
question.append(str(n1) + '-' + str(n2) + '=')
ans1.append(n1 - n2)
elif p == 3:
#乘法
n1 = random.randint(0, 20)
n2 = random.randint(0, 20)
question.append(str(n1) + '×' + str(n2) + '=')
ans1.append(n1 * n2)
elif p == 4:
#除法保证分母不为0
n1 = random.randint(0, 20)
if n1 == 0:
n2 = random.randint(1, 20)
else:
n2 = random.randint(1, n1 + 1)
question.append(str(n1) + '÷' + str(n2) + '=')
ans1.append(Fraction(n1, n2))
else:
print("输入错误!")
exit()
随机生成两个分数
def createF():
fz1 = random.randint(0, 20)
fm1 = random.randint(1, 20)#除法保证分母不为0
f1 = Fraction(fz1, fm1)
fz2 = random.randint(0, 20)
fm2 = random.randint(1, 20)#除法保证分母不为0
f2 = Fraction(fz2, fm2)
return f1, f2
两个分数的四则运算
def count2(question,ans1):
f1,f2 = createF()
print("欢迎来到分数的四则运算")
print("加法(请选1)减法(请选2)乘法(请选3)**除法(请选4)")
p = int(input())
if p == 1:
#加法
question.append(str(f1)+'+'+str(f2)+'=')
ans1.append(f1+f2)
elif p == 2:
#减法
f1,f2 = max(f1,f2),min(f1,f2)#保证出现的数字为正数
question.append(str(f1)+'-'+str(f2)+'=')
ans1.append(f1-f2)
elif p == 3:
#乘法
question.append(str(f1)+'×'+str(f2)+'=')
ans1.append(f1*f2)
else:
#除法
question.append(str(f1)+'÷'+str(f2)+'=')
ans1.append(Fraction(f1,f2))
主类
def main():
while 1:
print("0(退出)**1(整数题目)**2(分数题目)")
print("请输入你的选择")
p = int(input())
print("输入题目的数量" )
k = int(input())
temp = 100 / k
score = 0
question = []
ans1 = []
for i in range(k):
if p == 1:
count1(question, ans1)
elif p == 2:
count2(question, ans1)
elif p == 0:
exit()
else:
print("输入错误!")
for i in range(k):
print("第{}题:{}".format(i + 1,question[i]))
a = input()
if a == str(ans1[i]):
print("正确!")
score =score + temp
else:
print("错误!")
print("所得的分数为:{}".format(score))
print("题目的正确答案为:{}".format(ans1))
print("欢迎继续练习!", end=" ")
main()
PSP:
总结反思:
代码写的很爽!很nice!