2012-10-27 101 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版本,上面的轉換到應該是微不足道的。