如何计算多个操作?

时间:2019-08-01 11:58:31

标签: c# winforms

我只是从C#开始,希望一次进行多个计算(我正在创建一个基本计算器)。

我正在使用本教程(我知道它已经很老了,但是它仍然可以工作,并且我的计算器实际上可以计算,但是我不知道如何让它计算1个以上的运算,并且它只能执行单个运算,例如1/2或3 x 5):https://www.instructables.com/id/Creating-a-Calculator-Visual-Studio-C/

因此,我了解基本概念,它将您的第一个数字保存在一个隐藏变量中,将其从输入变量中删除,然后将您的运算符(- +随便什么)放入第二个隐藏变量中,最后是您的最终数字被添加到序列中,它们全部在操作中合并并计算,然后以表格的形式输出回输入框(我也对公式进行了一些调整,并且设法也得到负数!)。

这是我的项目CalcForYou的完整源代码:https://github.com/skylerspark/project-CalcForYou

我会像这样处理数字点击:

    string input = string.Empty;
    string operand1 = string.Empty;
    string operand2 = string.Empty;
    char operation;
    double result = 0.0;

    private void btn1_Click(object sender, EventArgs e)
    {
        this.flatTextBox1.Text = "";
        input += "1";
        this.flatTextBox1.Text += input;
    }

+ - / *单击如下:

    private void btnPlus_Click(object sender, EventArgs e)
    {
        operand1 = input;
        operation = '+';
        input = string.Empty;
    }

和我的相等按钮:

    private void flatButton1_Click(object sender, EventArgs e)
    {
        operand2 = input;
        double num1, num2;
        double.TryParse(operand1, out num1);
        double.TryParse(operand2, out num2);

        if (operation == '+')
        {
            result = num1 + num2;
            flatTextBox1.Text = "= " + result.ToString();
        }
        else if (operation == '-')
        {
            result = num1 - num2;
            flatTextBox1.Text = "= " + result.ToString();
        }
        else if (operation == '*')
        {
            result = num1 * num2;
            flatTextBox1.Text = "= " + result.ToString();
        }
        else if (operation == '/')
        {
            result = num1 / num2;
            flatTextBox1.Text = "= " + result.ToString();
        }
    }

0 个答案:

没有答案