问题
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