1

我觉得这有点奇怪。我的代码在运算符未更改的情况下工作,例如 2*2*2 给我 8 但是,当我更改运算符时不起作用 - 它转到最后一个运算符。也就是说,当我击中诸如:9 * 6 / 4 之类的东西时,它会阻止我在除法上,所以,它给了我 9 * 6,当我击中 / 时,会出现答案 1.5。这是来自未存储的操作员吗?任何含糊或准确的建议将不胜感激。这很奇怪,因为如果使用相同的运算符,它就可以工作......

public partial class Form1 : Form
{

    string buffer = " ";
    char op;
    double[] operand = new double[2];
    double result;
    int step = 1;

    public Form1()
    {
        InitializeComponent();
    }

    private void NumberButtons(object sender, EventArgs e)
    {
        Button b = sender as Button;

        buffer += b.Text;
        txtBox.Text = buffer;
    }

    private void Dot(object sender, EventArgs e)
    {
        if (!buffer.Contains('.'))
        {
            buffer = buffer + ".";
            txtBox.Text = buffer;
        }
    }

    private void Operations(object sender, EventArgs e)
    {
        Button b = (sender as Button);
        op = b.Text[0];
        if (buffer.Length == 0)
            operand[step - 1] = result;
        else
            operand[step - 1] = Double.Parse(buffer);
        if (step == 2)
        {
            Result(null, null);
            operand[0] = result;
            step = 2;
        }
        else
        { 
            txtBox.Text = operand[0].ToString();
            step++;
            buffer = "";
        }
    }
    private void Result(object sender, EventArgs e)
    {
        if (buffer.Length != 0)
            operand[1] = Double.Parse(buffer);
        switch (op)
        {
            case '+':
                result = operand[0] + operand[1];
                break;
            case '-':
                result = operand[0] - operand[1];
                break;
            case '*':
                result = operand[0] * operand[1];
                break;
            case '/':
                result = operand[0] / operand[1];
                break;
        }
        txtBox.Text = result.ToString();
        step = 1;
        buffer = " ";
    }
    private void Clear(object sender, EventArgs e)
    {
        if (buffer.Length == 0)
        {
            step = 1;
            operand[0] = operand[1] = 0.0;
            op = ' ';
            result = 0.0;
        }
        else
            buffer = "";
        txtBox.Text = buffer;
    }
}

}

4

0 回答 0