1

こんにちは、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);
4

4 に答える 4

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、上記のバージョンに変換するのは簡単です。

于 2012-10-27T15:32:12.747 に答える
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 に適用することもできますが、3 項ステートメントの方がはるかにクリーンです (パフォーマンスに違いがあると思いますが、確かではありません) - 個人的にはそのまま使用します。

三項演算子は、条件を記述する単純な方法であり、条件をインラインで追加するのに最も役立ちます (ここの場合のように)。構文は単純です。

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

それらは割り当てにも使用できます。

int myInt = aCondition ? 1 : -1;//Makes myInt 1 if aCondition is true, -1 if false
于 2012-10-27T12:54:59.610 に答える
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);そうでない場合は、コードが判読できなくなり、問題の修正がより複雑になり始めます。

于 2012-10-27T12:57:39.917 に答える
-1

GNU構文では、次のステートメントは同等です

condition ? a : b

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

後者はGNU拡張機能ですが、ほとんどのコンパイラでサポートされています。最初のものはインラインで書くのがはるかに簡単ですが

于 2012-10-27T13:04:24.053 に答える