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

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:

主站蜘蛛池模板: 沂南县| 阿图什市| 巫山县| 中牟县| 桐梓县| 凤山市| 依兰县| 乐昌市| 临桂县| 湾仔区| 三明市| 泉州市| 台前县| 安新县| 娄烦县| 和硕县| 凤凰县| 赤峰市| 青浦区| 长兴县| 桑日县| 天门市| 郓城县| 长子县| 札达县| 老河口市| 商城县| 历史| 建湖县| 福建省| 乌苏市| 孝昌县| 鄂温| 永新县| 博乐市| 揭东县| 通榆县| 孟连| 朝阳县| 罗源县| 湘潭市|