Scroll indicator done
728x90

[실습]

예제 3-1 ~ 3-23
연습문제 3.6 ~ 3.9


후위 연산으로 변경 후 수식 계산 (stack 이용)

1. 3+4*2
2. 3*4-2/1

using System;
using System.Collections.Generic;
using System.Text;

namespace HelloWorld {
    
    class Assignment1App {

        static void Main()
        {
            Console.Out.Write("수식 입력 : ");
            string input = Console.In.ReadLine();
            
            input = PostFix(input);  // 수식을 PostFix 방식으로 변환
            Console.Out.WriteLine("Postfix : " + input); // PostFix 후 결과 출력
            Stack<string> stack = new Stack<string>(); // 수식 연산을 위한 stack 선언
            for (int i = 0; i < input.Length; i++) 
            {
                string c = Convert.ToString(input[i]); 
                // c가 연산자가 아닐 때
                if (c != "+" && c != "-" && c != "*" && c != "/") stack.Push(c);
                else // c 가 연산자일 때
                {
                    int b = Convert.ToInt32(stack.Pop()); 
                    int a = Convert.ToInt32(stack.Pop());
                    
                    if (c == "+" || c == "-") 
                        stack.Push(Convert.ToString(c == "+" ? a + b : a - b)); 
                    else if (c == "*" || c == "/")
                        stack.Push(Convert.ToString(c == "*" ? a * b : a / b));
                }
            }
            Console.Out.Write("계산 결과 : " + stack.Pop() + "\n");
        }

        private static string PostFix(string s)
        {
            string result = null; 
            Stack<char> opr = new Stack<char>(); // 수식 stack
            Stack<char> output = new Stack<char>(); // 리턴할 결과 stack

            for (int i = 0; i < s.Length; i++) // 수식 길이 만큼
            {
                char tmp = s[i];
                if (tmp == '*' || tmp == '/') // 곱하기거나 나누기 연산자일 때
                {
                    // 스택 opr에 값이 존재하고 peek 값이 곱하기나 나누기 연산자일 때 반복
                    while (opr.Count != 0 && (opr.Peek() == '*' || opr.Peek() == '/'))
                        output.Push(opr.Pop()); 
                    opr.Push(tmp);
                }
                else if (tmp == '+' || tmp == '-') // 더하기거나 빼기 연산자일 때
                {
                    while (opr.Count != 0) // 스택 opr에 값이 존재할 때
                        output.Push(opr.Pop());
                    opr.Push(tmp);
                }
                else output.Push(tmp);
            }
            while (opr.Count != 0) output.Push(opr.Pop()); // 스택 opr이 비워질 때까지
            while (output.Count != 0) result += output.Pop(); // 스택 output이 비워질 때까지

            char[] res = result.ToCharArray();  // string 형의 결과값을 char Array 형식으로 변환
            Array.Reverse(res); // res 배열을 거꾸로 뒤집음
            return new string(res); // 배열을 다시 string 형으로 반환

        }
    }
}

728x90

'CLASS > C#' 카테고리의 다른 글

[C#] 2022.09.21 클래스, 문장  (2) 2022.09.21
[C#] 2022.09.14 C# 개요 및 실습  (0) 2022.09.14