c#做個計算機,想做個textbox ,把計算的程序記錄下來,button已賦值,但是textbox只能算出結果 ,沒有程序,如1+2+3,請問應該怎么令textbox有程序呢?
uj5u.com熱心網友回復:
存到一個字串變數里uj5u.com熱心網友回復:
臨時寫的,有點繁瑣。界面、程序、結果都有
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);
}
}
uj5u.com熱心網友回復:
有大概的代碼可以看看嗎?
uj5u.com熱心網友回復:
設定一個字串變數,假如是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里,當有了×÷時,自己增加()的邏輯。最后=的時候按照優先級依次提取出(),×÷,+-和數字,根據加減乘除自己做邏輯操作。uj5u.com熱心網友回復:

就像這樣,之后難的地方就是按=時進行拆分求解,之所以這樣做,到后面該計算器就可以擴容,不只是做加減乘除操作
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/94813.html
標籤:C#
上一篇:小白跪求,大佬進來
下一篇:在線求解決
