- 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:

- LabVIEW2018中文版 虛擬儀器程序設計自學手冊
- 算法零基礎一本通(Python版)
- Mastering OpenCV Android Application Programming
- C#完全自學教程
- AWS Serverless架構:使用AWS從傳統部署方式向Serverless架構遷移
- 零基礎玩轉區塊鏈
- DevOps入門與實踐
- Django:Web Development with Python
- C語言程序設計立體化案例教程
- C++程序設計基礎教程
- 利用Python進行數據分析(原書第3版)
- RabbitMQ Cookbook
- RealSenseTM互動開發實戰
- RESTful Java Web Services(Second Edition)
- Unity 2018 Shaders and Effects Cookbook