用python写代码,要求如下:随机生成两个两位数及加减号(要保证减法算式的被减数大于减数),显示题目让学生输入计算结果,判断并显示结果的正确与否(或给予累积得分)。可考虑设置答题结束条件为时间限制(如1分钟内完成)或题目总数限制(如20题),也可以是其它条件(自行设置)。
时间: 2023-05-23 15:06:37 浏览: 26
以下是ChitGPT回答:
可以使用Python的random模块来生成随机数和运算符,同时用if语句确保减法算式的被减数大于减数。以下是实现代码:
``` python
import random
import time
score = 0
total_questions = 20
time_limit = 60 # in seconds
start_time = time.time()
for i in range(total_questions):
# Generate two random two-digit numbers
num1 = random.randint(10, 99)
num2 = random.randint(10, 99)
# Generate random operator
operator = random.choice(['+', '-'])
# Ensure subtraction has positive result
if operator == '-' and num1 < num2:
num1, num2 = num2, num1
# Display question to user and get answer
print(f"Question {i+1}: What is {num1} {operator} {num2}?")
answer = int(input())
# Check answer and update score
if operator == '+':
correct_answer = num1 + num2
else:
correct_answer = num1 - num2
if answer == correct_answer:
print("Correct!")
score += 1
else:
print("Incorrect.")
# Check time limit
elapsed_time = time.time() - start_time
if elapsed_time >= time_limit:
print("Time's up!")
break
# Display final score
print(f"You scored {score}/{total_questions} in {elapsed_time:.1f} seconds.")
```
该代码生成20个随机算式,让用户输入答案并判断正确性。同时,根据设置的时间限制,如果时间到了就强制结束。最后展示用户得分和总用时。