2012-10-27 199 views
1

嘿家伙,我想知道如果用如果这里声明是在时代运营商难倒代码IM有写这不使用三元运营商的一种方式:三元运营商,以“if”语句

int x1 = place.getX(); 
int x2 = x1 + 
    ((direction == direction.NORTH || direction == direction.SOUTH ? shipLength : shipWidth) - 1) * 
    (direction == direction.NORTH || direction == direction.EAST ? -1 : 1); 
int y1 = place.getY(); 
int y2 = y1 + 
    ((direction == direction.NORTH || direction == direction.SOUTH ? shipWidth : shipLength) - 1) * 
    (direction == direction.WEST || direction == direction.NORTH ? -1 : 1); 
+5

是的,你可以用if/then构造来代替三元组。 – wildplasser

回答

0

这里的你怎么可以把X2到状态:

int x2 = x1 + shipWidth-1; 
if(direction == direction.NORTH || direction == direction.SOUTH) 
{ 
    x2 = x1 + shipLength-1; 
} 
if (direction == direction.NORTH || direction == direction.EAST) 
{ 
    x2 = -x2; 
} 

您可以应用同样的原理Y2,但三元陈述有很多清洁(我想可能有性能差异,不知道) - 我个人” d按原样使用它。

三元运算符仅仅是一个写作的条件更简单的方法,用于增加他们在线(比如这里的情况下)最有用的,语法很简单:

CONDITION ? (DO IF TRUE) : (DO IF FALSE) 

它们也可以在分配使用:

int myInt = aCondition ? 1 : -1;//Makes myInt 1 if aCondition is true, -1 if false 
0
int x1 = place.getX(); 
int x2 
if(direction == direction.NORTH || direction == direction.SOUTH){ 
    x2 = x1 + shipLength -1; 
    if(direction == direction.NORTH || direction == direction.EAST) 
     x2 *= -1; 
}else{ 
    int x2 = x1 + shipWidth-1; 
    if(direction == direction.NORTH || direction == direction.EAST) 
     x2 *= -1; 
} 

int y1 = place.getY(); 
int y2; 
if(direction == direction.NORTH || direction == direction.SOUTH){ 
    y2 = y1 + shipWidth-1; 
    if(direction == direction.NORTH || direction == direction.WEST) 
     y2 *= -1; 
}else{ 
    int y2 = y1 + shipLength-1; 
    if(direction == direction.NORTH || direction == direction.WEST) 
     y2 *= -1; 
} 

我觉得三元运营商是一个很好的选择,当该语句是小,像int x = (y == 10? 1 : -1);否则代码开始不可读和问题的修正是轧花是在GNU语法的更多复杂

+0

谢谢你似乎合乎逻辑 – Indrick

-1

以下语句是等价

condition ? a : b 

({if (condition) 
    a; 
else 
    b;}) 

后者是GNU扩展,它是由大多数编译器虽然支持。第一个是简单得多写,虽然

+0

TIL http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html – nibot

+0

你的例子不适合我。这确实有效:'({int x; if(condition)x = a; else x = b; x;})'。 – nibot

1

一个不太通心粉版在线:

int x1 = place.getX(); 
int y1 = place.getY(); 
int x2, y2; 
switch(direction) { 
case NORTH: 
    x2 = x1-(shipLength-1); 
    y2 = y1-(shipWidth-1); 
    break; 
case SOUTH: 
    x2 = x1+(shipLength-1); 
    y2 = y1+(shipWidth-1); 
    break; 
case EAST: 
    x2 = x1-(shipWidth-1); 
    y2 = y1+(shipLength-1); 
    break; 
case WEST: 
    x2 = x1+(shipWidth-1); 
    y2 = y1-(shipLength-1); 
    break; 
default: 
    x2 = x1+(shipWidth-1); 
    y2 = y1+(shipLength-1); 
    //printf("Your ship seems to be sinking!\n"); 
    //exit(1); 
} 

如果你想具体if - else if版本,上面的转换到应该是微不足道的。