根据提示,在右侧编辑区补充代码,完善一个能随机出题进行四则运算的小程序。 测试说明 平台会对你编写的代码进行测试: 测试输入: 1 4 7 预期输出: 请输入出题数量:请输入参与计算的最大数字:4+3=恭喜你,回答正确 答对1题,正确率为100.0%
时间: 2024-09-20 08:01:33 浏览: 54
Python一个随机生成四则运算题目的小程序
5星 · 资源好评率100%
首先,我们需要创建一个Python小程序,使用random模块来生成题目,并获取用户输入的答案,然后判断结果是否正确。这是一个简单的示例:
```python
import random
def generate_question(max_num):
a = random.randint(1, max_num)
b = random.randint(1, max_num)
operator = ['+', '-', '*', '/'][random.randint(0, 3)]
if operator == '/':
# 防止除数为零的情况
while b == 0:
b = random.randint(1, max_num)
return f"{a} {operator} {b}"
def check_answer(user_answer, correct_answer):
return user_answer == str(correct_answer)
def main():
test_input = [int(i) for i in input("请输入出题数量和参与计算的最大数字,用空格隔开:").split()]
num_questions = test_input[0]
max_number = test_input[1]
correct_answers = []
for _ in range(num_questions):
question = generate_question(max_number)
print(question)
user_answer = int(input("请输入你的答案:"))
correct_answer = eval(question) # 使用eval计算表达式的值
if check_answer(user_answer, correct_answer):
print(f"恭喜你,回答正确!{question}")
else:
print("回答错误,请再试一次!")
correct_answers.append(correct_answer)
total_correct = sum(1 for answer in correct_answers if answer is True)
accuracy = (total_correct / len(correct_answers)) * 100
print(f"答对了{total_correct}题,正确率为{accuracy:.2f}%")
if __name__ == "__main__":
main()
```
阅读全文