用python實現四則運算的生成與判定

Lucaba發表於2024-04-19

小組成員:2252316,2252326

點選檢視程式碼
import random

def generate_question():
    operators= ['+', '-', '*', '/']
    while 1:
        operator1 = random.choice(operators)
        operator2 = random.choice(operators)

        num1 = random.randint(1, 100)
        num2 = random.randint(1, 100)
        num3 = random.randint(1, 100)

        if operator2 == '/':
            num2 = num3 * random.randint(1, 10)
        if operator1 == '/':
            num1 = num2 * random.randint(1, 10)
        question = str(num1) + ' ' + operator1 + ' ' + str(num2) + ' ' + operator2 + ' ' + str(num3)
        answer = int(eval(question))
        if answer>0 and answer<100:
            break

    return question, answer


def generate_questions(num_questions):
    questions = []
    answers = []

    for _ in range(num_questions):
        question, answer = generate_question()
        questions.append(question)
        answers.append(answer)

    return questions, answers


def check_answer(question, user_answer):
    correct_answer = int(eval(question))
    return user_answer == correct_answer

num_questions = int(input("題目數量:"))
questions, answers = generate_questions(num_questions)

score = 0
for i in range(num_questions):
    print(f"Question {i + 1}: {questions[i]} = ?")
    user_answer = int(input("Your answer: "))

    if check_answer(questions[i], user_answer):
        print("Correct!\n")
        score += 1
    else:
        print(f"Wrong! The correct answer is: {answers[i]}\n")

print(f"Your final score is: {score}/{num_questions}")


透過隨機函式生成隨機運算子以及隨機的數字,其中對於除法的處理花了一些功夫,因為想要結果為整數,所以我採用倒推的方法,比如a/b/c,那麼就先隨機生成c,然後用c一個隨機數得到b,再一個隨機數得到a,這樣的辦法來實現,另外一點是由於python3中固定完成除法會保留浮點型,所以採用強制轉換成整型的方式來判斷,這次嘗試中我出現了很多記憶不準確的地方,小組合作商討互相糾錯才得以最終實現。

相關文章