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

- Mastering RStudio:Develop,Communicate,and Collaborate with R
- Java Web開(kāi)發(fā)就該這樣學(xué)
- Oracle GoldenGate 12c Implementer's Guide
- Visual Studio Code 權(quán)威指南
- Julia High Performance(Second Edition)
- Java程序設(shè)計(jì)教程
- 官方 Scratch 3.0 編程趣味卡:讓孩子們愛(ài)上編程(全彩)
- Java Web開(kāi)發(fā)基礎(chǔ)與案例教程
- Offer來(lái)了:Java面試核心知識(shí)點(diǎn)精講(框架篇)
- 編程真好玩:從零開(kāi)始學(xué)網(wǎng)頁(yè)設(shè)計(jì)及3D編程
- Python Geospatial Analysis Cookbook
- Scratch 3.0少兒游戲趣味編程
- Yii框架深度剖析
- Abaqus GUI程序開(kāi)發(fā)指南(Python語(yǔ)言)
- Learn Spring for Android Application Development