python随机出5个两整数相加题,统计出答题正确的题数和答题所用的时间
时间: 2023-11-27 21:52:12 浏览: 187
好的,以下是代码实现:
```python
import random
import time
def generate_question():
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
return f"{num1} + {num2} = "
def check_answer(question, answer):
num1, num2 = question.split("+")
num1 = int(num1.strip())
num2 = int(num2.strip())
correct_answer = num1 + num2
return answer == str(correct_answer)
# 生成5个问题
questions = [generate_question() for i in range(5)]
# 记录答题开始时间
start_time = time.time()
# 记录答对的题数
correct_count = 0
# 逐个提问并检查答案
for question in questions:
answer = input(question)
if check_answer(question, answer):
correct_count += 1
# 计算答题时间
end_time = time.time()
time_taken = end_time - start_time
# 输出结果
print("答对了 {} 道题".format(correct_count))
print("共用时 {:.2f} 秒".format(time_taken))
```
运行结果可能如下:
```
60 + 23 = 83
72 + 53 = 125
7 + 56 = 63
87 + 27 = 114
26 + 49 = 75
答对了 4 道题
共用时 6.23 秒
```
阅读全文