2025年8月2日 星期六

猜數字:程式隨機出題,程式自行解題

import random

import math

max = 100 # 最大數字

number = random.randint(1,max) # 程式隨機出題, 1~100 之間。

score = int(math.sqrt(max))+1 # 起始分數為最大數字開根號加 1,若得到負分表示猜數的演算法不佳

got_it = False # False 表示還沒有答對,True 表示答對了

times = 0 # 計算共猜了多少次

# 演算法:用持續限縮範圍法,一直把可能的最小數字和最大數字加總除以 2 ,直到猜中為止。

low = 1 # 可能的最小數字

high = max # 可能的最大數字

print("Your initial score is " + str(score) +".")

while got_it == False: # 當還沒有猜對,就繼續猜

    times += 1 # 猜的次數加 1

    print("------------------") # 每次猜測相關數字的分隔線

    print("low = " + str(low)) # 現示最小可能數字

    print("high = " + str(high)) # 現示最大可能數字

    guess = int((low+high)/2) # 試猜數字 = 把可能的最小數字和最大數字加總除以 2 

    print("You guess " + str(guess) + ".")

    if guess > number: #  如果猜的數字太大

        score -= 1 # 扣一分

        high = guess-1 # 把最大可能數字改為試猜數字減 1

        print("Too big! Try again.") # 顯示所猜數字太大

        print("Your score is " + str(score) + ".") # 顯示目前分數

    elif guess < number: #  如果猜的數字太小

        score -= 1# 扣一分

        low = guess+1 # 把最小可能數字改為試猜數字加 1

        print("Too small! Try again.") # 顯示所猜數字太小

        print("Your score is " + str(score) + ".") # 顯示目前分數

    else: # 答對了

        got_it = True # 把 got_it 改為 True,表示答對了。原本是 False

        print("Congratulation! You got it!") # 顯示答對了

        print("Your have tried " + str(times) + " times.") # 顯示共猜了多少次

        print("Your score is " + str(score) + ".") # 顯示最後得分