Simple Calculator
이 초보자 연습은 Simple Calculator을 통해 핵심 문법과 문제 해결을 훈련합니다.
Simple Calculator이란?
이 초보자 연습은 Simple Calculator을 통해 핵심 문법과 문제 해결을 훈련합니다.
Simple Calculator 문제를 C와 C++의 실행 가능한 코드로 해결합니다.
중요한 점
- Compiler warning을 켜고 모두 해결하세요.
- 각 값의 type과 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으로 컴파일하세요.
- 선언과 구현을 분리하세요.