官术网_书友最值得收藏!

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.

To know more about operator precedence, refer to https://msdn.microsoft.com/en-us/library/aa691323(VS.71).aspx.

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:

主站蜘蛛池模板: 汶上县| 兰溪市| 论坛| 黔西县| 邮箱| 新龙县| 潮州市| 长泰县| 出国| 京山县| 南宁市| 汾阳市| 兰溪市| 称多县| 奉新县| 砀山县| 钟祥市| 奉节县| 正蓝旗| 南华县| 博罗县| 黄山市| 黎平县| 法库县| 翼城县| 恩平市| 乡宁县| 南投市| 苍山县| 县级市| 齐齐哈尔市| 曲松县| 波密县| 稷山县| 永平县| 饶平县| 介休市| 东乌珠穆沁旗| 宁海县| 许昌县| 承德县|