C# 在单个文本框中生成值以执行加法

C# 在单个文本框中生成值以执行加法,c#,C#,我最近被困在我的项目中,因为我有需要满足的需求,需要在单个文本框中执行加法。 我看过最相似的帖子,它给了我一个很好的想法 我需要使用double而不是int,就像使用int一样 private int i = 0; private int[] a = new int[2]; private void button1_Click(object sender, EventArgs e) { int b; if(Int32.TryParse(textBox1.Text, out b

我最近被困在我的项目中,因为我有需要满足的需求,需要在单个文本框中执行加法。 我看过最相似的帖子,它给了我一个很好的想法

我需要使用double而不是int,就像使用int一样

  private int i = 0;
private int[] a = new int[2];
private void button1_Click(object sender, EventArgs e)
{
    int b;
    if(Int32.TryParse(textBox1.Text, out b))
    {
        a[i] = b;
        i++;
        textBox1.Text = "";
    }
    else
    {
        MessageBox.Show(@"Incorrect number");
    }


}

private void resultbutton2_Click(object sender, EventArgs e)
{
    int sum = a[0] + a[1];
    MessageBox.Show("Sum: " + sum);
}
}

相反,我应该使用什么代码为double创建类似的东西

double b = 0;
try{
    b = Convert.ToDouble(textBox1.Text);
} 
catch(e){
   // Error Handling
}

文档:

您可以尝试使用以下内容:

Double.Parse("1.2");
这里有一些例子:
如果您想保留代码,只需执行以下操作:

private int i = 0;
private double[] a = new double[2];
private void button1_Click(object sender, EventArgs e)
{
   double b;
   if (Double.TryParse(textBox1.Text, out b))
   {
      a[i] = b;
      i++;
      textBox1.Text = "";
    }
    else
    {
       MessageBox.Show(@"Incorrect number");
    }
}

private void resultbutton2_Click(object sender, EventArgs e)
{
   double sum = a[0] + a[1];
   MessageBox.Show("Sum: " + sum);
}
但您可以尝试添加两个以上的翻倍:

private double result = 0.0;
private void button1_Click(object sender, EventArgs e)
{
   double b;
   if (Double.TryParse(textBox1.Text, out b))
   {
          result += b,
          textBox1.Text = "";
    }
    else
    {
       MessageBox.Show(@"Incorrect number");
    }
}

private void resultbutton2_Click(object sender, EventArgs e)
{
   MessageBox.Show("Sum: " + result);
}