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

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:

主站蜘蛛池模板: 阿瓦提县| 峨边| 泰宁县| 六枝特区| 阿坝县| 玉山县| 阆中市| 修武县| 定南县| 宁德市| 定兴县| 永济市| 广南县| 浦东新区| 平顺县| 纳雍县| 溧阳市| 江川县| 特克斯县| 大丰市| 潢川县| 庄浪县| 吉林市| 长沙县| 晴隆县| 凤山市| 喜德县| 深水埗区| 龙井市| 湖北省| 项城市| 永城市| 施甸县| 乐东| 威宁| 东乡族自治县| 新化县| 利川市| 启东市| 鹿泉市| 大名县|