四则运算
import random
def generate_question(operation):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
if operation == '+':
correct_answer = num1 + num2
elif operation == '-':
correct_answer = num1 - num2
elif operation == '*':
correct_answer = num1 * num2
elif operation == '/':
correct_answer = num1 / num2
else:
print("无效的运算符")
return None, None
return (num1, num2), correct_answer
def main():
total_questions = 0
correct_questions = 0
while True:
operation = input("请输入要进行的运算(+、-、*、/)或输入q退出:")
if operation == 'q':
break
(num1, num2), correct_answer = generate_question(operation)
user_answer = float(input(f"{num1} {operation} {num2} = "))
if abs(user_answer - correct_answer) < 1e-6:
print("回答正确")
correct_questions += 1
else:
print("回答错误")
total_questions += 1
print(f"正确率:{correct_questions / total_questions * 100}%")
if __name__ == "__main__":
main()
有一些小问题和改进点。首先,当进行除法运算时,如果num2是1以外的数,那么生成的答案将是一个浮点数。然而,程序在比较用户答案和正确答案时,使用了浮点数直接比较(这在Python中通常是不推荐的,因为浮点数运算可能会引入微小的误差)。此外,当输入无效的运算符时,程序会打印消息并返回None, None,但在main函数中并没有处理这种情况,这可能导致运行时错误。
下面是一个改进后的版本,它处理了这些潜在的问题:
import random
def generate_question(operation):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
if operation == '+':
correct_answer = num1 + num2
elif operation == '-':
correct_answer = num1 - num2
elif operation == '*':
correct_answer = num1 * num2
elif operation == '/':
# 避免除以0的情况,并确保答案为浮点数
if num2 == 0:
print("除数不能为0,已重新生成题目。")
return generate_question(operation) # 递归调用以重新生成题目
correct_answer = num1 / num2
else:
print("无效的运算符")
return None, None
return (num1, num2), correct_answer
def main():
total_questions = 0
correct_questions = 0
while True:
operation = input("请输入要进行的运算(+、-、*、/)或输入q退出:")
if operation == 'q':
break
result = generate_question(operation)
if result is None:
continue # 跳过无效的运算符输入
(num1, num2), correct_answer = result
# 当进行除法时,允许用户输入浮点数
if operation == '/':
user_answer = float(input(f"{num1} {operation} {num2} = "))
else:
# 对于其他运算,尝试将输入转换为整数,如果失败则转为浮点数
try:
user_answer = int(input(f"{num1} {operation} {num2} = "))
except ValueError:
user_answer = float(input("请输入一个有效的数字:"))
# 使用一个小的容差来比较浮点数
if abs(user_answer - correct_answer) < 1e-6:
print("回答正确")
correct_question