使用 C# 的基本计算器程序

来源:这里教程网 时间:2026-02-21 16:24:29 作者:

使用 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;
   }
}

相关推荐