当第二个数字为负时,乘法或除法不能正常工作

问题描述 投票:1回答:2

即时通讯尝试编写Windows 7s计算器,但我有问题只是乘法和除法。我在这里编写连接到multiply的代码,这样你就可以得到原因了。

    double input1;
    double input2;
    double result;
    string amalgar;

amalgar表示+或 - 或*或/

private void button14_Click(object sender, EventArgs e)
    {
        input1 = Convert.ToDouble(textBox1.Text);
        textBox1.Clear();
        amalgar = "*";


    }

这是为*按钮。

这是为了否定按钮:

private void button20_Click(object sender, EventArgs e)
    {
        input1 = Convert.ToDouble(textBox1.Text);
        input1 = input1 * (-1);
        textBox1.Text = input1.ToString();
    }

这是为了相同的按钮:

input2 = Convert.ToDouble(textBox1.Text);
if (amalgar == "*")
        {
            result = (input1 * input2);
            textBox1.Text = Convert.ToString(result);
        }

以下是结果的一些示例:

2*6=12      Right
 2*(-2)=4    Wrong
 (-2)*2=-4   R
 4*(-5)=25   W
 8*(-7)=49   W
 3*(-6)=36   W
 8/2=4       R
 8/(-2)=1    W
 8/(-3)=1    W
calculator division negative-number multiplying
2个回答
0
投票

这是因为当您点击否定按钮时,您将使用文本框内容的否定覆盖input1中的内容。

private void button20_Click(object sender, EventArgs e)
    {
        input1 = Convert.ToDouble(textBox1.Text); // These lines overwrite
        input1 = input1 * (-1);                   // anything in input1
        textBox1.Text = input1.ToString();
    }

因此,当您转到等于代码时,如果您按下的最后一项是负按钮,则输入2和输入1始终是相同的数字。

input2 = Convert.ToDouble(textBox1.Text); // this equals input1 if the last thing
                                          // you pressed was the negative button
if (amalgar == "*")
        { // ....

button20_Click中,您需要修改textBox1的内容而不覆盖input1。您可以尝试使用局部变量进行所有计算:

double modifiedInput = Convert.ToDouble(textBox1.Text);
modifiedInput = modifiedInput * (-1);
textBox1.Text = modifiedInput.ToString();

0
投票

我已经解决了。这是一个容易犯的错误。

问题是在negativation按钮,我试图将input1乘以-1。

我已将代码更改为:

input3 = Convert.ToDouble(textBox1.Text);
            qarine = input3 * (-1);
            textBox1.Text = qarine.ToString();

在该按钮和相同按钮中的一些子句:

else if (amalgar == "*")
        {
            if (input1 > 0 && input2 > 0)
            {
                result = (input1 * input2);
            }
            else if (input1 < 0 && input2 < 0)
            {
                result = (input1 * input2);
            }

            else if (input1 < 0 && input2 > 0)
            {
                result = (qarine * input2);
            }

            else if (input1 > 0 && input2 < 0)
            {
                result = (input1 * qarine);
            }

            textBox1.Text = Convert.ToString(result);
        }
© www.soinside.com 2019 - 2024. All rights reserved.