แบบฝึกหัด Rust
Fibonacci Sequence in Rust
Build the Fibonacci numbers with a loop, a tuple swap and a vector.
สิ่งที่คุณจะได้เรียนรู้
- A loop with two variables
- (a, b) = (b, a + b)
- Why u64
The first numbers
00
11
12
23
34
55
Each number is the sum of the two before
Each Fibonacci number is the sum of the two before it, starting from 0 and 1. Build the first numbers of the sequence in a vector.
a and b hold two neighbouring numbers. (a, b) = (b, a + b) moves both one step forward in a single assignment. u64 is used because Fibonacci numbers grow quickly: the 50th no longer fits in 32 bits.
ประเด็นสำคัญ
- Start from 0 and 1.
- One tuple assignment moves both values.
- u64 holds much larger numbers than u32.
ตัวอย่าง Rust ที่รันได้
Rust
main.rs
fn fibonacci(count: usize) -> Vec<u64> {
let mut sequence = Vec::with_capacity(count);
let (mut a, mut b) = (0u64, 1u64);
for _ in 0..count {
sequence.push(a);
(a, b) = (b, a + b);
}
sequence
}
fn main() {
println!("{:?}", fibonacci(10));
println!("50th: {}", fibonacci(50)[49]);
}
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
50th: 7778742049ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- เลขฟีโบนัชชี คืนค่าเลขฟีโบนัชชีลำดับที่ n ง่าย
- ผลรวมของจำนวนฟีโบนักชีที่เป็นเลขคู่ หาผลรวมของจำนวนฟีโบนักชีที่เป็นเลขคู่และไม่เกินค่าขีดจำกัดที่กำหนด ง่าย