嘿,伙计们,我想知道有没有一种不使用三元运算符的方法来写这个,通过使用if语句,这里是im在times运算符上难倒的代码:
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);
最佳答案
一个更少的斯帕盖蒂版本:
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
版本,那么将上面的内容转换为该版本应该很简单。关于c - 三元运算符“如果”声明,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13100308/