这道题我回答过的,不知道怎么被删除了。下面是上次回答的代码。
import random
cnt_n = int(input("题目数量:"))
max_n = int(input("最大数字:"))
# 产生乘法查找表
times_list = []
for i in range(max_n):
for j in range(max_n):
if i * j <= max_n:
qst = str(i) + "*" + str(j)
rst = str(i*j)
if qst not in times_list:
times_list.append([qst, rst])
# 题目表
question_list = []
for _ in range(cnt_n):
# 随机运算,0+,1-,2*,3/
op = random.randint(0, 3)
# +
if op == 0:
x1 = random.randint(0, max_n)
x2 = random.randint(0, max_n - x1)
result = x1 + x2
qst = str(x1) + "+" + str(x2) + "="
question_list.append([qst, result])
# -
elif op == 1:
x1 = random.randint(0, max_n)
x2 = random.randint(0, x1)
result = x1 - x2
qst = str(x1) + "-" + str(x2) + "="
question_list.append([qst, result])
# *
elif op == 2:
tmp = random.sample(times_list, 1)
qst = tmp[0][0] + "="
question_list.append([qst, tmp[0][1]])
# /
elif op == 3:
tmp = random.sample(times_list, 1)
x1, x2 = tmp[0][0].split("*")
result = tmp[0][1]
while int(x1) == 0:
tmp = random.sample(times_list, 1)
x1, x2 = tmp[0][0].split("*")
result = tmp[0][1]
qst = result + "/" + x1 + "="
question_list.append([qst, x2])
print("开始回答:")
wrong = ""
for i, qst in enumerate(question_list):
x = input("第{:>2d}题:{}".format(i+1, qst[0]))
if int(x) != int(qst[1]):
wrong += str(i+1) + " "
w_item = wrong.split()
print("回答正确{}道题目。".format(len(question_list) - len(w_item)))
print("回答错误的题号是:{}".format(wrong))
第一步,考虑加减乘除四种运算符的优先级,乘除优先,所以首先你进行运算的时候要考虑先生成乘除运算,然后才是加减运算。
第二部,就是依次迭代构造运算架构和运算数,格外需要关注除法运算,每一次检查除法的除数是否为0,可以每一步构造的时候生成中间结果,然后你构造完成的时候就直接给出结果。其他的细节你可以自己想想。