Simple Calculator
この初心者向け演習では、Simple Calculatorを通して基本構文と問題解決を練習します。
Simple Calculatorとは?
この初心者向け演習では、Simple Calculatorを通して基本構文と問題解決を練習します。
Simple CalculatorをCとC++の実行可能なコードで解きます。
重要なポイント
- compiler warningを有効にしてすべて修正します。
- 各値の型とlifetimeを把握します。
- 入力と配列の境界を検証します。
CとC++のコード例
C
main.c
#include <stdio.h>
int main(void) {
int left = 12, right = 4, result = 0; char operation = '*';
// Select the calculation from the operator.
switch (operation) { case '+': result = left + right; break; case '-': result = left - right; break; case '*': result = left * right; break; case '/': result = left / right; }
printf("%d %c %d = %d\n", left, operation, right, result);
}
12 * 4 = 48
C++
main.cpp
#include <iostream>
int main() {
int left = 12, right = 4, result = 0; char operation = '*';
// Select the calculation from the operator.
switch (operation) { case '+': result = left + right; break; case '-': result = left - right; break; case '*': result = left * right; break; case '/': result = left / right; }
std::cout << left << ' ' << operation << ' ' << right << " = " << result << '\n';
}
12 * 4 = 48
CとC++の比較
CとC++の実装を比較し、入力を変更して追加の境界ケースをテストしてください。
C
Cは小さな手続き型APIと表現の詳細を明示します。
C++
C++は低レベルモデルを保ちつつ安全な型を追加します。
練習課題
両方を実行して変更し、言語ごとの保証を確認します。
- 不正入力と境界値を追加します。
- -Wall -Wextra -Wpedanticでコンパイルします。
- 宣言と実装を分割します。