Decimal to Binary
이 초보자 연습은 Decimal to Binary을 통해 핵심 문법과 문제 해결을 훈련합니다.
Decimal to Binary이란?
이 초보자 연습은 Decimal to Binary을 통해 핵심 문법과 문제 해결을 훈련합니다.
Decimal to Binary 문제를 C와 C++의 실행 가능한 코드로 해결합니다.
중요한 점
- Compiler warning을 켜고 모두 해결하세요.
- 각 값의 type과 lifetime을 파악하세요.
- 입력과 배열 경계를 검증하세요.
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++ 비교
C와 C++ 구현을 비교하고 입력을 바꾼 뒤 추가 경계 사례를 테스트하세요.
C
C는 작은 절차형 API와 표현 세부 사항을 드러냅니다.
C++
C++는 저수준 모델을 유지하며 더 안전한 타입을 추가합니다.
연습 문제
두 버전을 실행하고 수정하여 각 언어의 보장을 관찰하세요.
- 잘못된 입력과 경계값을 추가하세요.
- -Wall -Wextra -Wpedantic으로 컴파일하세요.
- 선언과 구현을 분리하세요.