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}");
    }
}
相关推荐
(Charon)5 小时前
【C++/Qt】Qt 实现 MQTT 测试工具:连接 Broker、订阅主题与发布消息
开发语言·c++·qt
Ulyanov5 小时前
《现代 Python 桌面应用架构实战:PySide6 + QML 从入门到工程化》:动态数据仪表盘与 NumPy 可视化 —— 从标量到向量的数据驱动进化
开发语言·python·qt·架构·numpy
小短腿的代码世界5 小时前
Qt序列化与持久化深度解析:从QDataStream到自定义二进制协议
开发语言·数据库·qt
周末也要写八哥5 小时前
Golang语言与Rust语言的对比
开发语言·后端·golang
楼田莉子5 小时前
Linux网络:数据链路层
linux·服务器·开发语言·网络·c++·后端
不甘先生6 小时前
Go 四层架构实战:Handler + Service + Repository + Entity(清晰、可控、可演进)
开发语言·架构·golang
Yang-Never6 小时前
Git -> Git Worktree 工作树
android·开发语言·git·android studio
riNt PTIP6 小时前
GO 快速升级Go版本
开发语言·redis·golang
xingpanvip6 小时前
星盘接口开发文档:日运语料接口指南
android·开发语言·前端·css·php·lua
AI进化营-智能译站6 小时前
ROS2 C++开发系列01:在ROS2上编写第一个C++ hello word
开发语言·c++·ai·word