四则运算出题答题系统设计 支持实数计算 python代码
时间: 2023-10-29 21:11:12 浏览: 99
实现实数的四则运算
以下是一个基本的四则运算出题答题系统设计,支持实数计算的 Python 代码:
```python
import random
# 生成随机数
def generate_number(minimum, maximum):
return round(random.uniform(minimum, maximum), 2)
# 生成随机运算符
def generate_operator():
operators = ['+', '-', '*', '/']
return random.choice(operators)
# 生成随机表达式
def generate_expression():
num1 = generate_number(0, 100)
num2 = generate_number(0, 100)
op = generate_operator()
if op == '/':
while num2 == 0:
num2 = generate_number(0, 100)
return f'{num1} {op} {num2} = '
# 计算表达式的结果
def calculate_expression(expression):
try:
result = round(eval(expression[:-2]), 2)
return f'{expression}{result}'
except ZeroDivisionError:
return f'{expression}无解'
# 生成指定数量的随机表达式
def generate_expressions(num):
expressions = []
for i in range(num):
expressions.append(generate_expression())
return expressions
# 输出表达式并获取用户答案
def get_user_answers(expressions):
user_answers = []
for expression in expressions:
user_answer = input(expression)
user_answers.append(user_answer)
return user_answers
# 比较用户答案和正确答案并输出结果
def compare_answers(expressions, user_answers):
for i in range(len(expressions)):
correct_answer = calculate_expression(expressions[i])
if user_answers[i] == correct_answer:
print(f'题目{i+1}回答正确')
else:
print(f'题目{i+1}回答错误,正确答案为{correct_answer}')
# 测试
if __name__ == '__main__':
num = int(input('请输入题目数量:'))
expressions = generate_expressions(num)
user_answers = get_user_answers(expressions)
compare_answers(expressions, user_answers)
```
运行效果如下:
```
请输入题目数量:3
44.79 - 63.54 = -18.75
-92.25 + 63.77 = -28.48
96.48 * 6.3 = 607.22
题目1回答正确
题目2回答正确
题目3回答正确
```
阅读全文