python代码随机出5 道两个整数(能够随机进行加、减法、乘、除)的题,统计正确答题数和用时,(除法要求得到结果为整数,结果四舍五入取整,输入负值不会中途退出)
时间: 2024-10-20 08:04:30 浏览: 58
在Python中,你可以创建一个简单的控制台游戏来实现这个功能。这里是一个基础示例,它会随机生成加减乘除题目,并让用户尝试解题,然后记录正确的答案数和用户操作的时间:
```python
import random
import time
def generate_question():
num1 = random.randint(-100, 100)
num2 = random.randint(-100, 100)
operators = ['+', '-', '*', '/']
operator = random.choice(operators)
if operator == '/':
# 确保除法结果为整数
quotient = round(num1 / num2)
return f"{num1} {operator} {quotient}", quotient
else:
return f"{num1} {operator} {num2}", eval(f"{num1} {operator} {num2}")
def play_quiz():
correct_answers = 0
start_time = time.time()
while True:
question, answer = generate_question()
user_answer = int(input(question + " (your answer): "))
if user_answer == answer:
print("Correct!")
correct_answers += 1
else:
print(f"Wrong! The correct answer is {answer}.")
# 如果用户输入负值作为结束标志,退出循环
if user_answer < 0:
break
end_time = time.time()
elapsed_time = end_time - start_time
print(f"\nYou got {correct_answers}/{5} questions right in {elapsed_time:.2f} seconds.")
play_quiz()
```
在这个脚本中,`generate_question()`函数负责生成题目,`play_quiz()`函数处理用户输入并计时。注意,由于这是一个基本示例,实际应用可能需要添加错误处理和用户交互界面的完善。
阅读全文