要使用C#创建计算器程序,您需要使用Web窗体。在该按钮下,创建1-9,加,减,乘等按钮。
让我们看一下用于加法,减法和乘法的代码。首先,我们声明了两个变量-
static float x, y;
现在,我们将看到如何在单个按钮单击上设置用于计算的代码:由于我们也使用Windows窗体来显示计算器,因此结果文本框为tbResult-
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; } }