三元运算符为“if”语句

时间:2012-10-27 12:47:31

标签: c ternary-operator

嘿伙计们,我想知道是否有一种方法可以在不使用三元运算符的情况下通过使用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 个答案:

答案 0 :(得分:1)

少spagetti版本:

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版本,将上述内容转换为该内容应该是微不足道的。

答案 1 :(得分: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

答案 2 :(得分: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);,否则代码开始变得不可读,问题的纠正开始变得更加复杂

答案 3 :(得分:-1)

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

condition ? a : b

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

后者是GNU扩展,但大多数编译器都支持它。第一个更容易编写内联但