发布于 2015-08-16 14:47:33 | 82 次阅读 | 评论: 0 | 来源: 网络整理

运算符优先级决定的条款在表达式中的分组。这会影响一个表达式如何计算。某些运算符的优先级高于其他;例如,乘法运算符的优先级比加法运算符高。

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

这里,具有最高优先级的操作出现在表的顶部,那些具有最低出现在底部。在表达式中,优先级较高的运算符将首先计算。

分类  Operator  关联 
Postfix  () [] -> . ++ - -   Left to right 
Unary  + - ! ~ ++ - - (type)* & sizeof  Right to left 
Multiplicative   * / %  Left to right 
Additive   + -  Left to right 
Shift   << >>  Left to right 
Relational   < <= > >=  Left to right 
Equality   == !=  Left to right 
Bitwise AND  Left to right 
Bitwise XOR  Left to right 
Bitwise OR  Left to right 
Logical AND  &&  Left to right 
Logical OR  ||  Left to right 
Conditional  ?:  Right to left 
Assignment  = += -= *= /= %=>>= <<= &= ^= |=  Right to left 
Comma  Left to right 

例子

试试下面的例子就明白了在D编程语言中的运算符优先级可供选择:


import std.stdio;

int main(string[] args)
{
   int a = 20;
   int b = 10;
   int c = 15;
   int d = 5;
   int e;
   e = (a + b) * c / d;      // ( 30 * 15 ) / 5
   writefln("Value of (a + b) * c / d is : %dn",  e );
   e = ((a + b) * c) / d;    // (30 * 15 ) / 5
   writefln("Value of ((a + b) * c) / d is  : %dn" ,  e );
   e = (a + b) * (c / d);   // (30) * (15/5)
   writefln("Value of (a + b) * (c / d) is  : %dn",  e );
   e = a + (b * c) / d;     //  20 + (150/5)
   writefln("Value of a + (b * c) / d is  : %dn" ,  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
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务