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

更新于:2020 年 6 月 19 日

870 次浏览

开启你的 事业

完成课程获得认证

立即开始
广告
© . All rights reserved.