C# 实现加减乘除 (备忘)

请给出 计算表达式 (4+5.0)/ 4.2 * (3+5.3)

csharp 复制代码
using System;
using System.Collections.Generic;

public class ExpressionEvaluator
{
    public static double Evaluate(string expression)
    {
        var operands = new Stack<double>();
        var operators = new Stack<char>();

        for (int i = 0; i < expression.Length; i++)
        {
            char ch = expression[i];
            if (ch == ' ')
                continue;

            if (ch == '(')
            {
                operators.Push(ch);
            }
            else if (char.IsDigit(ch) || ch == '.')
            {
                string operand = ch.ToString();
                while (i + 1 < expression.Length && (char.IsDigit(expression[i + 1]) || expression[i + 1] == '.'))
                {
                    operand += expression[i + 1];
                    i++;
                }
                operands.Push(double.Parse(operand));
            }
            else if (ch == ')')
            {
                while (operators.Peek() != '(')
                {
                    ProcessOperator(operands, operators);
                }
                operators.Pop(); // Remove '('
            }
            else
            {
                while (operators.Count > 0 && Precedence(operators.Peek()) >= Precedence(ch))
                {
                    ProcessOperator(operands, operators);
                }
                operators.Push(ch);
            }
        }

        while (operators.Count > 0)
        {
            ProcessOperator(operands, operators);
        }

        return operands.Pop();
    }

    private static int Precedence(char op)
    {
        if (op == '+' || op == '-')
            return 1;
        if (op == '*' || op == '/')
            return 2;
        return 0;
    }

    private static void ProcessOperator(Stack<double> operands, Stack<char> operators)
    {
        char op = operators.Pop();
        double operand2 = operands.Pop();
        double operand1 = operands.Pop();
        double result = ApplyOperator(op, operand1, operand2);
        operands.Push(result);
    }

    private static double ApplyOperator(char op, double operand1, double operand2)
    {
        switch (op)
        {
            case '+':
                return operand1 + operand2;
            case '-':
                return operand1 - operand2;
            case '*':
                return operand1 * operand2;
            case '/':
                if (operand2 == 0)
                    throw new DivideByZeroException("Division by zero");
                return operand1 / operand2;
            default:
                throw new ArgumentException("Invalid operator");
        }
    }

    public static void Main(string[] args)
    {
        string expression = "(4+5.0)/4.2*(3+5.3)";
        double result = Evaluate(expression);
        Console.WriteLine($"Result of expression {expression} is {result}");
    }
}
相关推荐
Wang's Blog1 小时前
Java 项目实战: 交友项目:登录链路回顾与今日任务地图
java·开发语言·状态模式·交友
砚底藏山河2 小时前
python量化:行情数据回溯
java·开发语言·python·金融·maven
今年下半年2 小时前
AI智能体项目实战记录(02):初始化 Python 项目
开发语言·人工智能·python·fastapi
Williamtym2 小时前
PickGo Lab实践:用浏览器、Python和MCP串起机器人搬运仿真
开发语言·python·机器人
DongQiShanRen2 小时前
六根硬件映射(四):归属澄清、两处不一致与卷十一总表
开发语言·人工智能·算法·rust·哈希算法·集成学习
CS创新实验室2 小时前
Python 对象“死“了之后去了哪?——引用计数与分代垃圾回收
开发语言·jvm·python
quantdash_cc2 小时前
Pandas 处理分钟级股票行情:从原始数据清洗到 K 线聚合
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
yu_zhidun3 小时前
企业电脑监控软件怎么选:别只看功能清单,先看这 6 个底层能力
开发语言·电脑·php·域智盾系统
无忧.芙桃3 小时前
C++语言原理与实践(十六):多态机制讲解
开发语言·c++·多态
李纲明4 小时前
WordPress 白屏排查手册:关插件、换主题、开调试、查 PHP(附停手信号)
开发语言·php·wordpress·故障排查·白屏·插件冲突