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}");
    }
}
相关推荐
y = xⁿ5 分钟前
JUC八股:线程池及ThreadLocal
java·开发语言
01_ice9 分钟前
Java多态
java·开发语言
AI人工智能+电脑小能手25 分钟前
【大白话说Java面试题 第78题】【Mysql篇】第8题:解释下最左前缀原则?
java·开发语言·数据库·mysql·面试
彦楠1 小时前
指定Tomcat运行的JDK地址
java·开发语言·tomcat
csbysj20201 小时前
Rust 组织管理
开发语言
清水白石0081 小时前
构建企业级 Python 服务:配置、日志、指标与追踪的稳健之道
开发语言·python·elasticsearch
lsx2024061 小时前
特效(Effect)
开发语言
那小子、真烦1 小时前
Hermes Agent Chat 方法分析
java·开发语言
爱喝水的鱼丶1 小时前
SAP-ABAP:变量、常量、结构与内表声明(10篇博客合集) 第六篇:ABAP 7.40+新特性:声明语法的简化写法与兼容注意事项
运维·服务器·开发语言·学习·算法·sap·abap
上海合宙LuatOS1 小时前
Air8000低功耗指南
开发语言·物联网·php·lua