Пишу программу на С#. Я написал логику для вычитания трех чисел, но она показывает неправильный результат. Ниже моего кода. Любая помощь будет оценена.

private void btnSub_Click(object sender, EventArgs e)
    {
        if (ch != "-")
        {
            num1 =  num1 - double.Parse(textBox1.Text);
        }
        else
        {
            num1= Convert.ToInt32(textBox1.Text);
            ch = "";
        }

        textBox1.Text = "";

        op = "-";

        textBox1.Text += op;

    }

Мой полный код:

namespace Cal1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        static double num1, num2 = 0;
        string op;
        static string ch = "";


        private void button1_Click_1(object sender, EventArgs e)
        {
            if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
            {
                textBox1.Text = "";

                textBox1.Text = textBox1.Text + button1.Text;
            }
            else
            {
                textBox1.Text = textBox1.Text + button1.Text;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
            {
                textBox1.Text = "";

                textBox1.Text = textBox1.Text + button2.Text;
            }
            else
            {
                textBox1.Text = textBox1.Text + button2.Text;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
            {
                textBox1.Clear();
                textBox1.Text = textBox1.Text + button3.Text;
            }
            else
            textBox1.Text = textBox1.Text + button3.Text;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
            {
                textBox1.Clear();
                textBox1.Text = textBox1.Text + button4.Text;
            }
            else
                textBox1.Text = textBox1.Text + button4.Text;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
            {
                textBox1.Clear();
                textBox1.Text = textBox1.Text + button5.Text;
            }
            else
                textBox1.Text = textBox1.Text + button5.Text;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
            {
                textBox1.Clear();
                textBox1.Text = textBox1.Text + button6.Text;
            }
            else
                textBox1.Text = textBox1.Text + button6.Text;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
            {
                textBox1.Clear();
                textBox1.Text = textBox1.Text + button7.Text;
            }
            else
                textBox1.Text = textBox1.Text + button7.Text;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
            {
                textBox1.Clear();
                textBox1.Text = textBox1.Text + button8.Text;
            }
            else
                textBox1.Text = textBox1.Text + button8.Text;
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
            {
                textBox1.Clear();
                textBox1.Text = textBox1.Text + button9.Text;
            }
            else
                textBox1.Text = textBox1.Text + button9.Text;
        }

        private void button10_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
            {
                textBox1.Clear();
                textBox1.Text = textBox1.Text + button10.Text;
            }
            else
                textBox1.Text = textBox1.Text + button10.Text;
        }

        private void btnEqual_Click(object sender, EventArgs e)
        {
            double result;
            num2 = double.Parse(textBox1.Text);
            textBox1.Text = "";
            switch (op)
            {
                case "+":
                    result = num1 + num2;
                    textBox1.Text += result;
                    num1 = result;
                    ch = "+";
                    break;
                case "-":
                    result = num1 - num2;
                    textBox1.Text += result;
                    num1 = result;
                    ch = "-";
                    break;
                case "*":
                    result = num1 * num2;
                    textBox1.Text += result;
                     num1 = result;
                    ch = "*";
                    break;
                case "/":
                    result = num1 / num2;
                    textBox1.Text += result;
                    num1 = result;
                    ch = "/";
                    break;
            }
        }


        private void btnAdd_Click(object sender, EventArgs e)
        {

            if (ch != "+")
            {
                num1 = double.Parse(textBox1.Text)+ num1;
            }
            else
            {
                num1 = Convert.ToInt32(textBox1.Text);
                ch = "";
            }
            textBox1.Text = "";
            op = "+";

        }

        private void btnSub_Click(object sender, EventArgs e)
        {
            if (ch != "-")
            {
                num1 =  num1 - double.Parse(textBox1.Text);
            }
            else
            {
                num1= Convert.ToInt32(textBox1.Text);
                ch = "";
            }

            textBox1.Text = "";

            op = "-";

            textBox1.Text += op;

        }

        private void btnMul_Click(object sender, EventArgs e)
        {

            if (ch != "*")
            {
            num1 = double.Parse(textBox1.Text) * num1;
            }
            else
            {
                num1 = Convert.ToInt32(textBox1.Text);
                ch = "";
            }
            textBox1.Text = "";
            op = "*";

        }

        private void btnDiv_Click(object sender, EventArgs e)
        {

            if (ch != "/") 
            {
            num1 = double.Parse(textBox1.Text) / num1;
            }
            else
            {
                num1 = Convert.ToInt32(textBox1.Text);
                ch = "";
            }
            textBox1.Text = "";
            op = "/";


        }
-2
user3427653 19 Фев 2015 в 08:50
Ch является строкой, тогда вы можете использовать метод .Equal(). И вы не устанавливаете текст текстового поля для своего результата substaraction. textbox1.Text=num1.ToString()
 – 
Mahesh
19 Фев 2015 в 08:51
1
Я предполагаю, что он показывает только - в качестве вывода? Обычно лучше, когда вы отображаете значение, которое хотите отобразить. Вы сбрасываете его на "", затем добавляете -..
 – 
Pierre-Luc Pineault
19 Фев 2015 в 08:51
Он показывает неправильный вывод 7-4-3 я дал, он показывает 8
 – 
user3427653
19 Фев 2015 в 08:53
Попробуйте предоставить полный (по крайней мере, для этого метода) код, например, что такое ch и num1...
 – 
Devendra Soni
19 Фев 2015 в 08:55
Что вы имеете в виду, что вы даете 7-4-3, если вы вставляете его в textbox1, тогда ваш код выдает исключение в строке double.Parse(textbox1.Text)
 – 
Mahesh
19 Фев 2015 в 08:56

2 ответа

Прежде всего, поскольку все ваши методы с button1_Click_1 по button10_Click делают одно и то же, вы можете заменить их одним методом:

private void NumberButtonClicked(object sender, EventArgs e)
{
    var buttonClicked = (Button)sender;
    if (textBox1.Text == "+" || textBox1.Text == "-" || textBox1.Text == "*" || textBox1.Text == "/")
    {
        textBox1.Clear();
        textBox1.Text = textBox1.Text + buttonClicked.Text;
    }
    else
        textBox1.Text = textBox1.Text + buttonClicked.Text;
}

Тогда о вашей ошибке: в btnSub_Click вы проверяете поле ch, но никогда не устанавливаете для него значение (за исключением пустой строки ch = "") ... может быть, вы действительно хотите проверить op? Я не уверен ...

Другое дело с вашим методом btnDiv_Click. Там вы делите введенное значение на ранее введенное значение... не должно ли быть наоборот?

num1 = num1 / double.Parse(textBox1.Text);

Лучше всего было бы проверить это, и если это все еще не работает, вы устанавливаете точку останова в начале btnSub_Click, проверяете, какие значения имеют ваши переменные, когда вы щелкаете по ней, и отлаживаете метод, пошагово Это.

0
Hinek 19 Фев 2015 в 10:36

Проблема, вероятно, в том, что значения не очищаются после нажатия «равно». Давайте шаг за шагом рассмотрим ваш пример (7-4-3):

1) press 7:
textbox1.Text="7";

2) press -:
num1 =  num1 - double.Parse(textBox1.Text); = 7
ch = "";

3) press 4:
textbox1.Text="4";

4) press -:
num1 =  num1 - double.Parse(textBox1.Text); = 7-4 = 3
ch="";

5) press 3:
textbox1.Text="3";

6) press equals?
num2 = 3;
result = num1 - num2; = 3-3 = 0
textBox1.Text += result; = "0", which is correct
num1 = result; = 0 (accidentaly in this case, but sometimes another value will be left in here)

Вы не очищаете значения после нажатия равно, поэтому на последующие операции будет влиять предыдущее значение num1. Это не то, как обычно работают калькуляторы, поэтому я предполагаю, что это нежелательное поведение и, вероятно, ошибка, которая приводит к странным результатам в последующих операциях.

Если вы получаете правильные результаты при первой операции, но неправильные впоследствии, это должно быть причиной.

0
quetzy 19 Фев 2015 в 11:52