【发布时间】:2019-04-06 08:06:46
【问题描述】:
我正在学习正确性并努力寻找合适的循环不变量并证明其正确性。
我认为循环不变量应该是正值的 t=sum,但我不知道如何正确编写它或者是否有任何其他循环不变量?
SumPos(A[0..n - 1])
// Returns the sum of the positive numbers in an array A of length n. We
// assume that the sum of the numbers in an array of length zero is
zero.
t = 0
i = 0
while i != n do
if A[i] > 0
t = t + A[i]
i = i + 1
return t
【问题讨论】:
-
欢迎来到 SO。请阅读*.com/help/how-to-ask
-
非常感谢...第一次使用 *,我会改进...
-
循环不变量是在每次循环迭代之前和之后为真的条件。您的解决方案不正确,因为 t 只是最后一次迭代后 A 中所有正值的总和。
-
嗨,循环变体也是如此:{A[i]>0 and t = t + A[i] }正确吗?
标签: algorithm correctness