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

时间:2018-09-18 19:15:19

标签: calculator division negative-number multiplying

我试图编写Windows 7s计算器

,但是我在乘除法上有问题。在这里,我编写了相乘的代码,以便您了解原因。

    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

2 个答案:

答案 0 :(得分:0)

It's because when you hit the negative button, you overwrite what you had in input1 with the negative of the contents of the textbox.

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();
    }

So that when you go to the equals code, input 2 and input 1 are always the same number if the last thing you pressed was the negative button.

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

In button20_Click you need to modify the contents of textBox1 without overwriting input1. Something you could try is using a local variable to do all your calculations on:

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

答案 1 :(得分:0)

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

问题出在否定按钮上,我试图将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);
        }