- Learn C# in 7 days
- Gaurav Aroraa
- 252字
- 2021-07-08 09:51:26
Discussing operator precedence in C#
The calculation or evaluation of any expression and the order of operators is very important. This is what is called operator precedence. We have all read the mathematic rule Order of Operator, which is abbreviated as BODMAS. Refer to https://www.skillsyouneed.com/num/bodmas.html to refresh your memory. So, mathematics teaches us how to solve an expression; in a similar way, our C# should follow rules to solve or evaluate the expression. For instance, 3+2*5 evaluates as 13 and not 25. So, in this equation, the rule is to first multiply and then add. That's why it evaluates as 2*5 = 10 and then 3+10 = 13. You can set a higher precedence order by applying braces, so if you do this in the preceding statement (3+2)*5, it results in 25.
This is a simple code snippet to evaluate the expression:
private void OperatorPrecedence() { Write("Enter first number:"); Num1 = Convert.ToInt32(ReadLine()); Write("Enter second number:"); Num2 = Convert.ToInt32(ReadLine()); Write("Enter third number:"); Num3 = Convert.ToInt32(ReadLine()); Write("Enter fourth number:"); Num4 = Convert.ToInt32(ReadLine()); int result = Num1 + Num2 * Num3/Num4; WriteLine($"Num1 + Num2 * Num3/Num4 = {result}"); result = Num1 + Num2 * (Num3 / Num4); WriteLine($"Num1 + Num2 * (Num3/Num4) = {result}"); result = (Num1 + (Num2 * Num3)) / Num4; WriteLine($"(Num1 + (Num2 * Num3)) /Num4 = {result}"); result = (Num1 + Num2) * Num3 / Num4; WriteLine($"(Num1 + Num2) * Num3/Num4 = {result}"); ReadLine(); }
The preceding code produces the following results:

- oreilly精品圖書:軟件開發者路線圖叢書(共8冊)
- 從零開始學Linux編程
- Web前端應用開發技術
- Creating Data Stories with Tableau Public
- 運維前線:一線運維專家的運維方法、技巧與實踐
- 計算機應用基礎項目化教程
- Application Development with Parse using iOS SDK
- Practical Maya Programming with Python
- 軟件測試技術
- Android初級應用開發
- 算法精解:C語言描述
- Bitcoin Essentials
- Learn Linux Quickly
- C語言編程魔法書:基于C11標準
- Java面試一戰到底(基礎卷)