Sister寫的版本

@@"



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

namespace Joy
{
    class Program
    {
        static void Main(string[] args)
        {
            CStack s = new CStack(10);
            string tmp,str = "23-53+*";
            int a, b,c=0;
            char op;
            Console.WriteLine("算式:" + str);
            for (int i = 0; i < str.Length;i++ )  // Length是判斷 字串長度
            {
                tmp = str.Substring(i,1);  // 是 字串 由 第 i 個字 取 1個
                if (char.IsNumber(str,i)) // IsNumber 是判斷 取得的字串是否為數字
                {
                    s.push(tmp); //將數字丟進堆疊
                }
                else {
                    a = int.Parse(s.pop()); // int.Parse 是將字串解析為整數
                    b = int.Parse(s.pop()); //POP資料出來
                    op = str[i]; //拿字串陣列的第i個
                   
                    switch(op){
                        case '+':
                            c = a + b;
                            break;
                        case '-':
                            c = a-b;
                            break;
                        case '*':
                            c = a * b;
                            break;
                        case '/':
                            c = a / b;
                            break;
                        default: //若非以上情況則執行
                            Console.WriteLine("error");
                            break;
                   
                    }
                    s.push(c.ToString());//將結果push回堆疊
                }
            }
            Console.WriteLine("運算結果:"+ s.pop());//顯示運算結果
            Console.Read();
        }
    }
    class CArray {  // 堆疊類別的定義
        protected string[] d;
        public CArray(int n){
            d = new string[n];
        }
    }
    class CStack : CArray{  //顯示堆疊狀態
        private int sp;
        public CStack(int n): base(n){
            sp = 0;
        }
        public void push(string data){
            if(sp == d.Length){
                Console.WriteLine("full");
            }else{
                Console.WriteLine("push "+data+" 到第[" + sp + "]的位置");
                d[sp] = data;
                sp++;
            }
        }
        public string pop()
        {
            if(sp == 0){
                Console.WriteLine("empty");
                return "";
            }else{
                sp--;
                Console.WriteLine("pop位置 [" + sp + "] 的資料");
                return d[sp];
            }
        }
    }
}

 


arrow
arrow
    全站熱搜

    Joy 發表在 痞客邦 留言(0) 人氣()