c#做个计算机,想做个textbox ,把计算的过程记录下来,button已赋值,但是textbox只能算出结果 ,没有过程,如1+2+3,请问应该怎么令textbox有过程呢?

解决方案 »

  1.   

    临时写的,有点繁琐。界面、过程、结果都有public Form1()
            {
                InitializeComponent();            Button button = new Button() { Size = new Size(0, 0), Location = new Point(0, 0) };
                this.Controls.Add(button);            TextBox textBox = new TextBox() {Size = new Size(300,25), Location = new Point(10,10),ReadOnly = true,};
                textBox.GotFocus += (sender, e) => { button.Focus(); };
                this.Controls.Add(textBox);            int setx = 0, sety = 0;
                string[] btn_numtext = new string[] { "1","2","3","4","5","6","7","8","9","清零",".","0"};
                for (int i = 0; i < 12; i++)
                {
                    Button button_num = new Button() { Size = new Size(40, 40), Location = new Point(10+setx *60,50+sety*60),Text = btn_numtext[i]};
                    if (i==9) button_num.Click += (sender, e) => { textBox.Clear(); };
                    else button_num.Click += (sender, e) => { textBox.Text += button_num.Text; };
                    setx += 1;
                    if ((i + 1) % 3 == 0 && setx != 0) { setx = 0; sety += 1; }
                    this.Controls.Add(button_num);
                }            setx = 0; sety = 0;
                string[] btn_opertext = new string[] { "+", "×", "-", "÷","删除","=" };
                for (int i=0;i<6;i++)
                {
                    Button button_oper = new Button() { Size = new Size(40, 40),Location = new Point(200 + setx * 60, 50 + sety * 60),Text = btn_opertext[i]};
                    if (i == 4) button_oper.Click += (sender, e) => { textBox.Text = textBox.Text.Substring(0, textBox.Text.Length - 1); };
                    else if (i==5) button_oper.Click += (sender, e) => { 
                        DataTable dt = new DataTable();
                        try { textBox.Text = dt.Compute(textBox.Text.Replace("×","*").Replace("÷", "/"), null).ToString(); } catch { MessageBox.Show("not an expression"); }
                    };
                    else button_oper.Click += (sender, e) => { textBox.Text += button_oper.Text; };
                    setx += 1;
                    if ((i + 1) % 2 == 0 && setx != 0) { setx = 0; sety += 1; }
                    this.Controls.Add(button_oper);
                }
            }
      

  2.   

    设置一个字符串变量,假如是a,每次点击除去=的按钮时,就在a里增加这个值然后显示在textbox里,比方说你先点1,a="1",textbox里就是1,再点击+,a变成字符串"1+",textbox里也是1+,再点击2,a变成"1+2",textbox也是如此,假如点击了"1+2+3",再点击=时就对字符串序列进行操作,按照+进行拆分出1,2,3来,依次对其进行+的操作。过程的话用个字符串代替就行了。有时可能是1+2+3×2,键盘这样输入,字符串序列肯定不对,我们想要的其实是(1+2+3)×2,那么你可以自己设计逻辑。比如当只是+-的时候,字符串按照原先显示在textbox里,当有了×÷时,自己增加()的逻辑。最后=的时候按照优先级依次提取出(),×÷,+-和数字,根据加减乘除自己做逻辑操作。