在循环中为x和y设计一个公式来满足这些要求

Devise a formula inside a loop for x and y to satisfy these requirements

本文关键字:一个 满足 循环      更新时间:2023-10-16

根据下列要求,设计一个计算x和y的公式

given:  length1   length2, assume length1 >= length2
total = length1 + length2

i = 0                : x = 0,          y = 0
i = 1                : x = 0,          y = 1
...
i = length2 -1       : x = 0,          y = length2 -1
i = total-length1    : x = 0,          y = 0
i = total-length1 +1 : x = 1,          y = 0
...
i = length1 + length2: x = length1 -1, y = 0
所以在代码中,它看起来像:
int length1 = //given
int length2 = //given
int total = length1 + length2;
for (int i = 0; i < total; i++) {
    x = ?  //answer here
    y = ?  //answer here
}

下面是一个length1 = 5的例子;length2 = 4

 i   x,y
---------
i=0  0,0 
i=1  0,1  
i=2  0,2
i=3  0,3
i=4  0,0
i=5  1,0  
i=6  2,0  
i=7  3,0  
i=8  4,0

编辑:我正在寻找一个1-liner来查找x和y。
当i小于length2时将x约分为0当i大于length1时将y约分为0

if (i < length2) {
  x = 0;
  y = i;
} else {
  x = i - length2;
  y = 0;
}

如何:

if (i < length2) {
    x = 0;
    y = i;
} else {
    x = i - length2;
    y = 0;
}
相关文章: