当前位置: 首页 > 文档资料 > 学习 C 语言 >

Show 例子 7

优质
小牛编辑
120浏览
2023-12-01

运算符优先级确定表达式中的术语分组,并决定如何计算表达式。 某些运算符的优先级高于其他运算符; 例如,乘法运算符的优先级高于加法运算符。

例如,x = 7 + 3 * 2; 这里,x被赋值为13,而不是20,因为operator *的优先级高于+,所以它首先乘以3 * 2然后加到7中。

此处,具有最高优先级的运算符显示在表的顶部,具有最低优先级的运算符显示在底部。 在表达式中,将首先评估更高优先级的运算符。

类别操作者关联性
Postfix()[] - >。 ++ - -左到右
Unary+ - ! 〜++ - - (类型)*&sizeof右到左
Multiplicative* /%左到右
Additive+ -左到右
Shift<< >>左到右
Relational<< => =左到右
Equality==!=左到右
Bitwise AND&左到右
Bitwise XOR ^左到右
Bitwise OR |左到右
Logical AND &&左到右
Logical OR ||左到右
Conditional?:右到左
Assignment= + = - = * =/=%= >> = << =&= ^ = | =右到左
Comma,左到右

例子 (Example)

尝试以下示例以了解C中的运算符优先级 -

#include <stdio.h>
main() {
   int a = 20;
   int b = 10;
   int c = 15;
   int d = 5;
   int e;
   e = (a + b) * c/d;      // ( 30 * 15 )/5
   printf("Value of (a + b) * c/d is : %d\n",  e );
   e = ((a + b) * c)/d;    // (30 * 15 )/5
   printf("Value of ((a + b) * c)/d is  : %d\n" ,  e );
   e = (a + b) * (c/d);   // (30) * (15/5)
   printf("Value of (a + b) * (c/d) is  : %d\n",  e );
   e = a + (b * c)/d;     //  20 + (150/5)
   printf("Value of a + (b * c)/d is  : %d\n" ,  e );
   return 0;
}

编译并执行上述程序时,会产生以下结果 -

Value of (a + b) * c/d is : 90
Value of ((a + b) * c)/d is  : 90
Value of (a + b) * (c/d) is  : 90
Value of a + (b * c)/d is  : 50