首页 文章

通过按下按钮键入C#计算器

提问于
浏览
0

我正在学习C#,所以我正在做一些练习来习惯C#语法并学习更好 . 我决定让计算器看起来像普通的Windows计算器一样 .

我只创建了一个按钮"1"和一个文本框 .
enter image description here

当我按下它时,我想让这个按钮在文本框中写1,并使int变量等于教科书中的数字,以便稍后进行计算 . 所以我不能改变“int a”的值或更改文本框中的文本,它总是显示01,因为a总是等于0.我如何制作程序,都显示正确的数字并更改值一个正确吗?例如,当我按两次按钮并将“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)
    {

    }
}

5 回答

  • 0

    你有几个选择:

    使int成为可以为null的int . 这样你就可以检查int是否已经设置好了

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

    检查textBox1的Text属性是否为空(这意味着您不必附加到它)

    if ( textBox1.Text == string.Empty)
    {
    }
    else
    {
    }
    
  • 0
    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
    
  • 0

    对于要将文本追加到文本框的任何按钮,将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
    }
    
  • 3
    private void button1_Click(object sender, EventArgs e)
    {
         textBox1.Text += "1";
    }
    
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        a = Int32.Parse(textBox1.Text);    
    }
    

    只需它..每次按钮点击都会更改textBox上的文本,并更改每个textBox更改后的变量 .

  • 2

    然后可以使用设置该值

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

    虽然如果你想更有效率,

    a = a * 10 + 1;
    

    根本没有 Sa

    textBox1.Text = a.ToString();
    

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

相关问题