import random
def generate_math_questions(num_questions):
questions = set() # 使用集合来确保题目不重复
while len(questions) < num_questions:
num1 = random.randint(1, 30)
num2 = random.randint(1, 30)
operator = random.choice(['+', '-', '*', '/'])
# 保证除法运算结果是整数
if operator == '/':
if num1 % num2 != 0:
continue # 重新生成题目
answer = num1 // num2 # 使用整数除法以确保整数结果
else:
answer = eval(f"{num1} {operator} {num2}") # 使用eval计算其他运算
question = f"{num1} {operator} {num2} = ?"
questions.add((question, answer))
return list(questions) # 转换为列表形式返回
num_questions = 20
questions = generate_math_questions(num_questions)
print("Here are your math questions:")
for i, (question, answer) in enumerate(questions, 1):
print(f"Question {i}: {question}")
print("Now, let's check your answers.")
score = 0
for i, (question, answer) in enumerate(questions, 1):
user_answer = input(f"Your answer for Question {i}: ")
try:
user_answer = int(user_answer)
except ValueError:
print(f"Invalid input! Please enter an integer.\n")
continue
if user_answer == answer:
print("Correct!\n")
score += 1
else:
print(f"Wrong! The correct answer is {answer}\n")
print(f"You answered {score} out of {num_questions} questions correctly.")
代码保证题目数量可选、确保题目不重复、