본문 바로가기
Computer Science

계산기2

by OKOK 2019. 1. 22.

1. 전위표기법 -> 후위표기법

2. 계산하는 방법

3.  스택 사용법


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
 
char infix[1001];
char postfix[1001];
int stack[1001];
int top;
 
void push(int num) {
    stack[++top] = num;
}
 
int pop() {
    return stack[top--];
}
 
int main() 
{
    freopen("input.txt""r", stdin);
    int T;
    int length;
    int idx;
    int res;
    int tmp1, tmp2;
    int i;
 
    for (T = 1; T <= 10++T)
    {
        top = -1;
        idx = 0;
        res = 0;
        scanf("%d"&length);
        scanf("%s", infix);
        for (i = 0; i < length; ++i)
        {
            if ((infix[i] >= '0'&& (infix[i] <= '9'))
                postfix[idx++= infix[i];
            else if (infix[i] == '+'// 우선순위 낮음
            {
                while ((top > -1&& ((stack[top] == '+'|| stack[top] == '*'))
                    postfix[idx++= pop();
                push(infix[i]);
            }
            else if (infix[i] == '*'// 우선순위 높음
            {
                while ((top > -1&& (stack[top] == '*'))
                    postfix[idx++= pop();
                push(infix[i]);
            }
        }
        while (top > -1)
            postfix[idx++= pop(); // stack에 남아 있는 것 모두 옮기기
        
        // 계산 시작
        for (i = 0; i < idx; ++i)
        {
            if ((postfix[i] >= '0'&& (postfix[i] <= '9'))
                push(postfix[i] - '0');
            else if (postfix[i] == '+')
            {
                tmp2 = pop();
                tmp1 = pop();
                push(tmp1 + tmp2);
            }
            else if (postfix[i] == '*')
            {
                tmp2 = pop();
                tmp1 = pop();
                push(tmp1 * tmp2);
            }
        }
        printf("#%d %d\n", T, pop());
    }
    return 0;
}
cs

 


'Computer Science' 카테고리의 다른 글

미로1  (0) 2019.01.22
암호생성기  (0) 2019.01.22
계산기1  (0) 2019.01.22
magnetic  (0) 2019.01.22
GNS  (0) 2019.01.22

댓글