ลำดับฟีโบนัชชี
สร้างจำนวนฟีโบนัชชีสิบตัวแรก
ลำดับฟีโบนัชชี คืออะไร?
จำนวนฟีโบนัชชีแต่ละตัวคือผลรวมของสองค่าก่อนหน้า
ประเด็นสำคัญ
- เปิด compiler warning และแก้ทุกคำเตือน
- รู้ type และ lifetime ของทุกค่า
- ตรวจ input และขอบเขต array ให้ชัดเจน
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
int main(void) {
int first = 0, second = 1;
for (int i = 0; i < 10; ++i) {
printf("%s%d", i ? " " : "", first);
// Advance the pair without storing the whole sequence.
int next = first + second; first = second; second = next;
}
puts("");
}
0 1 1 2 3 5 8 13 21 34
C++
main.cpp
#include <iostream>
int main() {
int first = 0, second = 1;
for (int i = 0; i < 10; ++i) {
if (i) std::cout << ' ';
std::cout << first;
// Advance the pair without storing the whole sequence.
int next = first + second; first = second; second = next;
}
std::cout << '\n';
}
0 1 1 2 3 5 8 13 21 34
เปรียบเทียบ C และ C++
ใช้ตัวแปรสถานะแค่สองตัวก็พอ เพราะแต่ละรอบต้องการแค่คู่ก่อนหน้า
C
C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน
C++
C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- เพิ่ม input ผิดและค่าขอบเขต
- Compile ด้วย -Wall -Wextra -Wpedantic
- แยก declaration และ implementation
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด