通过用栈来计算简单的算术表达式

本文介绍了一个使用C#实现的简单表达式求值程序。该程序通过两个栈(一个用于存储运算数,另一个用于存储运算符)来解析并计算字符串形式的数学表达式。文章展示了如何定义IsNumberic方法来验证字符是否为数字,并提供了Calculate和Compute方法的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Text.RegularExpressions;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack num = new Stack();
            Stack oper = new Stack();
            string expression = "12 + 56 + 77";
            Calculate(num, oper, expression);
            Console.WriteLine(num.Pop());
            Console.ReadKey();



            
        }

        //IsNumberic isn't built into C# so we must define it
        static bool IsNumberic(string input)
        {
            bool flag = true;
            string patten = (@"^\d+$");
            Regex validate = new Regex(patten);     
            if (!validate.IsMatch(input))
            {
                flag =false;
            }
            return flag;           
        }
        //N栈存放运算数,O栈存放运算符,
        static void Calculate(Stack N, Stack O, string exp)
        {
            string ch, token = "";
            for (int p = 0; p < exp.Length; p++)
            {
                ch = exp.Substring(p, 1);
                if (IsNumberic(ch))
                    token += ch;
                if (ch == " " || p == exp.Length - 1)
                {
                    if (IsNumberic(token))
                    {
                        N.Push(token);
                        token = "";
                    }
                }
                else if (ch == "+" || ch == "-" || ch == "*" || ch == "/")       
                    O.Push(ch);
                if (N.Count==2)
                    Compute(N, O);
               
            }
            
        }
        static void Compute(Stack N, Stack O)
        {
            int oper1, oper2;           
            string oper;                
            oper1 = Convert.ToInt32(N.Pop());
            oper2 = Convert.ToInt32(N.Pop());
            oper = Convert.ToString(O.Pop());
            switch (oper)
            {
                case "+":
                    N.Push(oper1 + oper2);
                    break;
                case "-":
                    N.Push(oper1 - oper2);
                    break;
                case "*":
                    N.Push(oper1 * oper2);
                    break;
                case "/":
                    N.Push(oper1 / oper2);
                    break;
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值