跳轉到內容

Rust 初學者程式設計/基礎數學測試程式/檢查數字

來自華夏公益教科書,為開放世界提供開放書籍

檢查數字

[編輯 | 編輯原始碼]

現在,我們希望驗證使用者輸入的數字是否等於兩個數字運算後的結果。首先,讓我們計算一下這個數字。為此,將兩個數字和運算子作為結構體的一部分是有意義的,因為這三個值經常一起使用,將它們放在一起會很方便,這樣我們就可以在結構體上定義函式,以使程式碼更清晰。讓我們像這樣定義結構體

struct MathsQuestion {
    left: i32,
    right: i32,
    operator: Operator,
}

結構體通常情況下,定義一個 new() 函式來方便構造結構體會很方便。我們可以這樣做

impl MathsQuestion {
    fn new(left: i32, right: i32, operator: Operator) -> MathsQuestion {
        MathsQuestion {
            left,
            right,
            operator,
        }
    }
}

注意,由於變數的名稱與結構體中欄位的名稱相同,因此我們不需要寫出

left: left,
right: right,
operator: operator,

這是一個很好的便利。此外,我們使用的是隱式返回,沒有分號,因此我們不需要寫 return。

現在,我們可以將我們的 print_question() 函式更改為該新結構體上的方法,因此我們在 impl MathsQuestion {} 塊中新增以下函式

fn print(&self) {
    println!("What is {} {} {}?", self.left, self.operator, self.right);
}

現在,我們可以在 MathsQuestion 結構體上編寫一個函式來計算結果,這個函式也位於 impl MathsQuestion {} 塊中

fn calc_result(&self) -> i32 {
    match self.operator {
        Operator::Addition => self.left + self.right,
        Operator::Subtraction => self.left - self.right,
    }
}

現在,我們可以將我們的 main() 函式更改為

fn main() {
    let question = MathsQuestion::new(35, 23, Operator::Subtraction);
    question.print();
    let val = wait_for_input();
    let result = question.calc_result();
    if val == result {
        println!("You got it correct! Well done!");
    } else {
        println!("Incorrect! The correct answer was {}", result);
    }
}

現在它可以工作了!如果我們輸入 12(即 35 - 23),我們得到正確的訊息,如果我們輸入任何其他數字,我們得到錯誤的訊息!

接下來:我們使用外部箱子使生成的數字隨機化

華夏公益教科書