แบบฝึกหัด Go

Fibonacci Sequence in Go

Build the Fibonacci numbers with a loop, a double assignment and a slice.

  • ระดับเริ่มต้น
  • อ่าน 2 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • A loop with two variables
  • a, b = b, a+b
  • Why uint64
The first numbers
00
11
12
23
34
55
5 = 2 + 3

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 slice.

a and b hold two neighbouring numbers. a, b = b, a+b moves both one step forward in a single assignment. uint64 is used because Fibonacci numbers grow quickly: the 50th no longer fits in 32 bits.

ประเด็นสำคัญ

  1. Start from 0 and 1.
  2. One assignment moves both values.
  3. uint64 holds much larger numbers than int32.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
main.go
package main

import "fmt"

func fibonacci(count int) []uint64 {
	sequence := make([]uint64, 0, count)
	a, b := uint64(0), uint64(1)
	for i := 0; i < count; i++ {
		sequence = append(sequence, a)
		a, b = b, a+b
	}
	return sequence
}

func main() {
	fmt.Println(fibonacci(10))
	fmt.Println("50th:", fibonacci(50)[49])
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
[0 1 1 2 3 5 8 13 21 34]
50th: 7778742049

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Structs →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด