使用 C# 的基本計算器程式
要使用 C# 建立一個計算器程式,你需要使用 Web 窗體。然後,建立 1-9、加號、減號、乘號等按鈕。
我們來看看加法、減法和乘法的程式碼。首先,我們聲明瞭兩個變數 −
static float x, y;
現在,我們來看看如何在各個按鈕單擊時設定運算程式碼:我們的結果文字框是 tbResult,因為我們還使用了 Windows 窗體來顯示計算器 −
protected void add_Click(object sender, EventArgs e) { x = Convert.ToInt32(tbResult.Text); tbResult.Text = ""; y = '+'; tbResult.Text += y; } protected void sub_Click(object sender, EventArgs e) { x = Convert.ToInt32(tbResult.Text); tbResult.Text = ""; y = '-'; tbResult.Text += y; } protected void mul_Click(object sender, EventArgs e) { x = Convert.ToInt32(tbResult.Text); tbResult.Text = ""; y = '*'; tbResult.Text += y; }
等號按鈕的程式碼如下 −
protected void eql_Click(object sender, EventArgs e) { z = Convert.ToInt32(tbResult.Text); tbResult.Text = ""; if (y == '/') { p = x / z; tbResult.Text += p; x = d; } else if (y == '+') { p = x + z; tbResult.Text += p; a = d; } else if (y == '-') { p = x - z; tbResult.Text += p; x = p; } else { p = x * z; tbResult.Text += p; x = p; } }
廣告