EXPRESSION CALCULATION

• Question

• HOW TO CALCULATE EXPRESSION IN c#

LIKE 51+25/28+1-(85*87)+54+36*98-45

Friday, May 18, 2018 8:13 AM

All replies

• Homework questions?

Expression based calculator is a popular homework for secondary school to practice "string tokenizing" and "stack manipulation"/"tree transversal" technique.

EDIT: added "tree transversal" because I've seen solutions based on both approach.

Tips: On the process of tokenizing the string, if you keep track of the operator precedence level and add missing parenthesis on precedence level change, the calculator logic can be significantly simplified.

Friday, May 18, 2018 10:03 AM
• For simple cases:

string example = "51+25/28+1-(85*87)+54+36*98-45";

var dt = new DataTable();

dt.Columns.Add( "r", typeof( double ), example );

double result = (double)dt.Rows[0][0];

Console.WriteLine( example );

Console.WriteLine( result );

Friday, May 18, 2018 10:28 AM
• Hi VIVEK KUMAR VERMA,

Thank you for posting here.

If you want to calculate this expression in c#, here is a simple example for your reference. You could do it directly in C#.

`int rsult = 51 + 25 / 28 + 1 - (85 * 87) + 54 + 36 * 98 - 45;`

Best Regards,

Wendy

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

Monday, May 21, 2018 3:07 AM