C# read and calculate multiple values from textbox [closed]

筅森魡賤 提交于 2021-02-11 17:59:09

问题


I have a question about creating calculator in C# Windows Form Application. I want it to be possible write with form buttons an expression in textbox so for example 2+3+7= and after pressing "=" button program will read all digits and signs and perform calculation... I don't know from where to start and how could do it in such a way. Any help to any reference or smth to look at how to start doing such a expressions?

Main thing is how to read, seperate and after calculate values from textbox.

Thanks.


回答1:


With the Split method you could solve this rather easy. Try this:

private void button1_Click(object sender, EventArgs e)
{
  string[] parts = textBox1.Text.Split('+');
  int intSum = 0;
  foreach (string item in parts)
  {
    intSum = intSum + Convert.ToInt32(item);
  }
  textBox2.Text = intSum.ToString();
}

If you would like to have a more generic calculation, you should look at this post: In C# is there an eval function?

Where this code snippet would do the thing:

public static double Evaluate(string expression)
{
  System.Data.DataTable table = new System.Data.DataTable();
  table.Columns.Add("expression", string.Empty.GetType(), expression);
  System.Data.DataRow row = table.NewRow();
  table.Rows.Add(row);
  return double.Parse((string)row["expression"]);
}

private void button1_Click(object sender, EventArgs e)
{
  textBox2.Text = Evaluate(textBox1.Text).ToString();
}


来源:https://stackoverflow.com/questions/20920314/c-sharp-read-and-calculate-multiple-values-from-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!