用Python编写一个随机出5个两整数相加题,统计出答题正确的题数和用时
时间: 2024-01-21 16:19:32 浏览: 192
可以使用random库来生成随机数,time库来计算答题用时。下面是代码实现:
```python
import random
import time
correct_count = 0 # 记录答题正确的数量
start_time = time.time() # 记录开始时间
for i in range(5):
num1 = random.randint(1, 100) # 生成随机数1
num2 = random.randint(1, 100) # 生成随机数2
result = num1 + num2 # 计算结果
# 提示用户输入答案,并转为int类型
answer = int(input(f"What is {num1} + {num2}? "))
# 判断答案是否正确
if answer == result:
print("Correct!")
correct_count += 1
else:
print("Incorrect!")
end_time = time.time() # 记录结束时间
total_time = end_time - start_time # 计算总用时
print(f"\nYou got {correct_count} out of 5 questions correct.")
print(f"Total time: {total_time:.2f} seconds")
```
运行示例:
```
What is 35 + 47? 82
Correct!
What is 19 + 65? 84
Incorrect!
What is 73 + 94? 167
Correct!
What is 5 + 77? 82
Correct!
What is 95 + 6? 101
Correct!
You got 4 out of 5 questions correct.
Total time: 15.22 seconds
```
阅读全文