不在运算符应用中存储运算符

时间:2013-09-04 23:28:17

标签: c# windows

我发现这有点奇怪。我的代码适用于不更改运算符的情况,例如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;
    }
}

}

0 个答案:

没有答案