【问题标题】:C# Calculator typing by pressing buttons通过按下按钮输入 C# 计算器
【发布时间】:2011-12-28 13:07:59
【问题描述】:

我现在正在学习 C#,所以我正在做一些练习来习惯 C# 语法并学得更好。我决定制作一个看起来像普通 Windows 计算器的计算器。

我只创建了一个按钮“1”和一个文本框。

我想让这个按钮在我按下它时在文本框中写 1 并且还使一个 int 变量等于教科书中的数字,以便稍后进行计算。所以我不能更改“int a”的值或更改文本框中的文本,它总是显示 01,因为 a 总是等于 0。 如何制作程序,既显示正确的数字又正确更改 a 的值? 例如,当我按两次按钮并将“int a”的值更改为 11 时,如何让程序在文本框中显示 11?

public partial class Form1 : Form
{
    int a;
    string Sa;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Sa = a.ToString() + "1";

        textBox1.Text = Sa;
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }
}

【问题讨论】:

  • 您的问题不清楚。你知道字符串和整数的区别吗?您确实了解 a.ToString() + "1" 是字符串而不是整数。所以它会简单地将 1 连接到字符串。
  • 在前一个文本之前追加文本:textBox1.Text = "1" + textBox1.Text;

标签: c# calculator


【解决方案1】:
private void button1_Click(object sender, EventArgs e)
{
     textBox1.Text += "1";
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    a = Int32.Parse(textBox1.Text);    
}

只是它.. 每次单击按钮更改文本框上的文本,并更改​​每个文本框更改的变量。

【讨论】:

    【解决方案2】:

    然后可以使用设置值

    a = int.Parse(Sa);
    textBox1.Text = Sa.TrimStart('0');
    

    虽然如果您想提高效率,

    a = a * 10 + 1;
    

    根本没有Sa

    textBox1.Text = a.ToString();
    

    如果遇到整数溢出,应该使用BigInteger

    【讨论】:

      【解决方案3】:

      您有多种选择:

      将 int 设为可为空的 int。这样你就可以检查 int 是否已经设置了

      int? a;
      
      if ( a.HasValue )
      {
      }
      else
      {
      }
      

      检查 textBox1 的 Text 属性是否为空(这意味着您不必在其上附加 a)

      if ( textBox1.Text == string.Empty)
      {
      }
      else
      {
      }
      

      【讨论】:

        【解决方案4】:
        public void btnOne_Click(object sender, EventArgs e)
                {
                    txtDisplay.Text = txtDisplay.Text + btnOne.Text;
        
                }
        
                private void btnTwo_Click(object sender, EventArgs e)
                {
                    txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
                }
        
        // etc 
        

        【讨论】:

          【解决方案5】:

          对于您想要将文本附加到文本框的任何按钮,请将 click 属性设置为 btn_Click,然后将此代码放入方法中

          private void btn_Click(object sender, EventArgs e)
          {
              Button btn = (Button)sender;
              // This will assign btn with the properties of the button clicked
              txt_display.Text = txt_display.Text + btn.Text;
              // this will append to the textbox with whatever text value the button holds
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-04-11
            • 2022-01-11
            • 2017-06-07
            • 2016-07-09
            • 2019-02-28
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多