Decimal to Binary
この初心者向け演習では、Decimal to Binaryを通して基本構文と問題解決を練習します。
Decimal to Binaryとは?
この初心者向け演習では、Decimal to Binaryを通して基本構文と問題解決を練習します。
Decimal to BinaryをCとC++の実行可能なコードで解きます。
重要なポイント
- compiler warningを有効にしてすべて修正します。
- 各値の型と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でコンパイルします。
- 宣言と実装を分割します。