gpt4 book ai didi

c - "if"语句的三元运算符

转载 作者:太空宇宙 更新时间:2023-11-04 04:53:01 25 4
gpt4 key购买 nike

嘿伙计们,我想知道是否有一种方法可以在不使用三元运算符的情况下通过使用 if 语句来编写此代码,这是我在 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 - "if"语句的三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13100308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com