일지
인터프리터...24
niamdank
2020. 12. 9. 11:56
역 폴란드 표기법 프로그램
실행 및 테스트
ReversePolish.h
#pragma region 실행 처리
// a ~ z를 각각 변수이고 1 ~ 26이 저장되었다고 가정한다.
int GetValue(char ch)
{
if (islower(ch))
{
return ch - 'a' + 1;
}
return 0;
}
int Execute()
{
int num1, num2;
char* str{ polish_result };
top = 0;
while(*str != '\0')
{
// 변수 처리
if (islower(*str))
{
Push(GetValue(*str));
}
// 숫자 처리
else if (isdigit(*str))
{
Push(*str - '0');
}
// 연산자 처리
else
{
num2 = Pop();
num1 = Pop();
switch (*str)
{
case '+':
Push(num1 + num2);
break;
case '-':
Push(num1 - num2);
break;
case '*':
Push(num1 * num2);
break;
case '/':
if (num2 == 0)
{
std::cout << "0으로 나눔\n";
exit(1);
}
Push(num1 / num2);
break;
}
}
str++;
}
// 결과가 제대로 저장되지 않은 경우
if (top != 1)
{
std::cout << "결과가 존재하지 않음\n";
exit(1);
}
return Pop();
}
#pragma endregion
ReversePolish.cpp
#include "ReversePolish.h"
int main()
{
char expression[80];
std::cout << "입력: ";
std::cin.getline(expression, 80);
Polish(expression);
// 유효하지 않은 식인 경우
if (polish_result[0] == '\0')
{
exit(1);
}
int result{ Execute() };
std::cout << "변환: " << polish_result << '\n';
std::cout << "결과: " << result << '\n';
}
실행 결과
입력: a+b+c
변환: ab+c+
결과: 6
-----------------------
입력: a+b*c
변환: abc*+
결과: 7
-----------------------
입력: (a+b)*5
변환: ab+5*
결과: 15
더보기