แบบฝึกหัด C/C++ สำหรับผู้เริ่มต้น

Decimal to Binary

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Decimal to Binary

Decimal to Binary คืออะไร?

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Decimal to Binary

แก้โจทย์ Decimal to Binary ด้วย code C และ C++ ที่รันได้

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

  • เปิด compiler warning และแก้ทุกคำเตือน
  • รู้ type และ lifetime ของทุกค่า
  • ตรวจ input และขอบเขต array ให้ชัดเจน

ตัวอย่างโค้ด C และ C++

C
รันโค้ด →
main.c
#include <stdio.h>
int main(void) {
    unsigned number = 13, value = number; int bits[32], count = 0;
    // Store remainders generated from right to left.
    do { bits[count++] = value % 2; value /= 2; } while (value);
    printf("%u = ", number); while (count) printf("%d", bits[--count]); puts("");
}
ผลลัพธ์ที่คาดหวัง
13 = 1101
C++
รันโค้ด →
main.cpp
#include <bitset>
#include <iostream>
#include <string>
int main() {
    unsigned number = 13;
    // Remove leading zeroes from a fixed-width bitset string.
    std::string bits = std::bitset<32>(number).to_string();
    bits.erase(0, bits.find_first_not_of('0'));
    std::cout << number << " = " << bits << '\n';
}
ผลลัพธ์ที่คาดหวัง
13 = 1101

เปรียบเทียบ C และ C++

เปรียบเทียบ implementation ของ C และ C++ จากนั้นเปลี่ยน input และทดสอบ edge case เพิ่มเติม

C

C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน

C++

C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า

แบบฝึกหัด

รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา

  • เพิ่ม input ผิดและค่าขอบเขต
  • Compile ด้วย -Wall -Wextra -Wpedantic
  • แยก declaration และ implementation