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

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:

主站蜘蛛池模板: 绍兴县| 偏关县| 杂多县| 策勒县| 容城县| 精河县| 耒阳市| 孙吴县| 张家界市| 桓台县| 湾仔区| 西华县| 阿克苏市| 三门县| 旬邑县| 体育| 安福县| 自贡市| 乌什县| 离岛区| 滦平县| 肃宁县| 哈尔滨市| 辉南县| 南乐县| 中西区| 建平县| 鹤峰县| 治县。| 鹤峰县| 思南县| 岳池县| 蓬溪县| 禹州市| 桦川县| 东乡| 昭通市| 江北区| 镶黄旗| 昌吉市| 五家渠市|