728x90
후위표기법(postfix notation)으로 표현된 하나의 수식을 파일(input.txt)로 입력받아 그 계산 결과를 화면에 출력하는 프로그램을 작성하라. 사용되는 연산자 : +, -, *, /, % 이며, 피연산자는 1~9 사이의 한 자리 정수이다.
입력파일(“input.txt”) : 82/3-42*+
화면출력 : 82/3-42*+
(입력수식의 문자열 길이는 최대 80으로 함)
사용되는 연산자 : +, -, *, / 사용되는 피연산자 : 1~9 사이의 한 자리 정수
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef enum {
FILE_OPEN_ERROR
};
#define NAME(a) #a
#define CATCH(error) do{printf(NAME(error)); exit(0);}while(false)
#define MAX_EXPR_SIZE 80
char expr[80];
typedef enum {
plus, minus, muliple, divide, operand, eos
} token_type;
char symbol;
int index_expr = 0;
token_type token_expr;
token_type get_token(void);
token_type token;
int eval(void);
int stack[MAX_EXPR_SIZE];
int top = -1;
void push(int data);
int pop(void);
#define FILE_NAME "input.txt"
int main(void)
{
FILE* fp;fopen_s(&fp, FILE_NAME, "r");
if (fp)
{
fscanf_s(fp, "%s", expr, sizeof(expr));
fclose(fp);
}
else CATCH(FILE_OPEN_ERROR);
printf("postfix expression : %s\n", expr);
printf("result : %d\n", eval());
return 0;
}
token_type get_token(void)
{
symbol = expr[index_expr++];
switch (symbol)
{
case '+': return plus;
case '-': return minus;
case '*': return muliple;
case '/': return divide;
case '\0': return eos;
default: return operand;
}
}
void push(int data)
{
stack[++top] = data;
}
int pop(void)
{
return stack[top--];
}
int eval(void)
{
token = get_token();
int op1, op2;
while (token != eos)
{
switch (token)
{
case plus: op2 = pop(); op1 = pop(); push(op1 + op2); break;
case minus: op2 = pop(); op1 = pop(); push(op1 - op2);break;
case muliple: op2 = pop(); op1 = pop(); push(op1 * op2);break;
case divide: op2 = pop(); op1 = pop(); push(op1 / op2);break;
case operand: push(symbol - '0'); break;
}
token = get_token();
}
return pop();
}
728x90
'data structure with C' 카테고리의 다른 글
Linked List (0) | 2020.12.20 |
---|---|
중위표기를 후위표기로 (0) | 2020.12.19 |
미로 탐색 (0) | 2020.12.18 |
Circular Queue of Dynamic Allocation Array (0) | 2020.12.17 |
Linear Queue of Static Allocation Array (0) | 2020.12.16 |