1

嘿,伙计们,我想知道是否有一种方法可以在不使用三元运算符的情况下通过使用 if 语句来编写此代码,这是我在 time 运算符时遇到的代码:

 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
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 回答
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,但三元语句更清晰(我认为可能存在性能差异,不确定) - 我个人会按原样使用它。

三元运算符只是编写条件的一种更简单的方法,对于内联添加它们最有用(就像这里的情况一样),语法很简单:

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 回答
-1

在 GNU 语法中,以下语句是等价的

condition ? a : b

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

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

于 2012-10-27T13:04:24.053 回答