这段代码是一个计算器中的核心方法之一,用于执行算术运算。它首先从 nums(数字)和 opes(运算符)栈中取出两个数字和一个运算符,然后根据运算符执行相应的算术运算(加减乘除、取模、乘方),并将结果 d 压入 nums 栈中。如果除数为零则会弹出一个错误提示框,如果运算符无法识别也会弹出错误提示框。最后,如果 nums 栈中只剩下一个数字,就将 opess 栈中的最后一个运算符弹出。

void call()
{
    if (nums.Count <= 1)
    {
        if (opes.Count >= 0)
            opes.Pop();
        return;
    }
    double a = (double)nums.Peek(); nums.Pop();
    double b = (double)nums.Peek(); nums.Pop();
    char c = (char)opes.Peek(); opes.Pop();
    double d = 0;
    if (c == '+') d = b + a;
    else if (c == '-') d = b - a;
    else if (c == '*') d = b * a;
    else if (c == '÷')
    {
        if (a != 0)
            d = b / a;
        else
        {
            MessageBox.Show('除数不能为零');
        }
    }
    else if (c == '^')
    {
        d = Math.Pow(b, a);
    }
    else if (c == '%') d = b % a;
    else
    {
        MessageBox.Show('错误!');
    }

    nums.Push(d);
}
C# 算术运算方法 - void call() 代码解析

原文地址: https://www.cveoy.top/t/topic/otlY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录