我正在将一些 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
,则将 vector.dot
方法的结果分配给 candidateMax
并检查 max
是否小于 candidateMax
。如果是,则继续迭代”。
这是正确的吗?我认为我误解了 while
条件的计算顺序。
最佳答案
我相信您的循环退出条件错误。
原文:
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/C 的 do ... 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) )
关于java - 在条件句中何时发生此分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60029547/