1

我正在将一些 Java 代码移植到 Xojo,它没有与 Java 相同的语言结构。

我在端口中有一个错误,我想我已经将它缩小到这段 Java 代码:

int maxIndex = 0;
int n = vertices.length; // vertices is an array
double max = dot(vertices[0]), candidateMax; // I'm assuming `candidateMax` is being initialised to 0 here.

if (max < (candidateMax = vector.dot(vertices[1]))) {
  // Search to the right
  do {
    max = candidateMax;
      maxIndex++;
  } while ((maxIndex + 1) < n && max < (candidateMax = vector.dot(vertices[maxIndex + 1])));

} else if ( max < (candidateMax = vector.dot(vertices[n - 1])) ) {
  maxIndex = n;
  // Search to the left
  do {
    max = candidateMax;
     maxIndex--;
  } while (maxIndex > 0 && max <= (candidateMax = vector.dot(vertices[maxIndex - 1])));
}
return maxIndex;

我已将其移植到此代码中(Xojo - 比上面的代码更详细):

Var maxIndex As Integer = 0
Var n As Integer = Vertices.Count
Var max As Double = vector.Dot(Vertices(0))
Var candidateMax As Double

candidateMax = vector.Dot(Vertices(1))
If max < candidateMax Then
  // Search to the right.
  Do
    max = candidateMax
    maxIndex = maxIndex + 1

    // Exit?
    If maxIndex + 1 >= n Then
      Exit
    Else
      candidateMax = vector.Dot(Vertices(maxIndex + 1))
      If max > candidateMax Then Exit
    End If
  Loop
Else
  candidateMax = vector.Dot(Vertices(n - 1))
  If max < candidateMax Then
    maxIndex = n

    // Search to the left.
    Do
      max = candidateMax
      maxIndex = maxIndex - 1

      // Exit?
      If maxIndex <= 0 Then
        Exit
      Else
        candidateMax = vector.Dot(Vertices(maxIndex - 1))
        If max > candidateMax Then Exit
      End If
    Loop
  End If
End If

Return maxIndex

我假设while循环有条件:

if (max < (candidateMax = vector.dot(this.vertices[1]))) {
  // Search to the right
  do {
    max = candidateMax;
      maxIndex++;
  } while ((maxIndex + 1) < n && max < (candidateMax = vector.dot(vertices[maxIndex + 1])));

翻译为:“至少执行一次循环的内容。在循环的每次迭代之后,检查是否maxIndex + 1小于n。如果不是,则退出循环。如果maxIndex + 1大于则将方法n的结果分配给and检查是否小于。如果是,则继续迭代“。vector.dotcandidateMaxmaxcandidateMax

它是否正确?我想我误解了while条件被评估的顺序。

4

1 回答 1

2

我相信您的循环退出条件错误。

原来的:

while (maxIndex > 0 && max <= (candidateMax = vector.dot(vertices[maxIndex - 1])))

在 Xojo 中大概意味着:

  ...
  if maxIndex > 0 then candidateMax = vector.Dot(Vertices(maxIndex - 1))
while (maxIndex > 0) and (max <= candidateMax)

通常,您可以将 Java/Cdo ... while (b)转换为 Xojo 的do ... loop until not (b).

这意味着,在你的情况下:

  ...
  if maxIndex > 0 then candidateMax = vector.Dot(Vertices(maxIndex - 1))
loop until not ( (maxIndex > 0) and (max <= candidateMax) )
于 2020-02-02T19:19:02.790 回答