dafny - 错误 BP5005:循环可能不会维护此循环不变量
问题描述
我是达夫尼的新手。我不明白为什么我收到这条消息时x == Sum(i);
我开始失去理智。还有为什么它编译if n==0 then 0 else n + Sum(n-1)
的时候变成if n==0 then 0 else n-1 + Sum(n-1)
function Sum(n: nat): nat
{
if n==0 then 0 else n + Sum(n-1)
}
method ComputeSum(n: nat) returns (x: nat)
ensures x == Sum(n);
{
x := 0;
var y := 0;
var i : nat := 0;
while i < n
invariant 0 <= i <= n && x == Sum(i);
{
x,y := y,x + y ;
i := i + 1;
}
}
解决方案
关于您的第二个问题:如果您更改if n==0 then 0 else n + Sum(n-1)
为if n==0 then 0 else n-1 + Sum(n-1)
,则对于每个 n,Sum(n) 的值都是 0。这符合 ComputeSum,它为所有输入 n 返回 0。
推荐阅读
- android - Android JobIntentService 在循环之间停止
- python - Jupyter中的格式化表
- sql - 从 SQL Server 获取特定的不同列
- firebase - 关于谷歌智能家居令牌交换问题的行动
- android - 如何将源集添加到android项目
- php - 如何在 CentOS 上为 PHP 7.4 安装日历功能?
- r - 函数中for循环和return的区别
- generics - 是否可以在泛型方法中指定任意可变参数列表?
- security - 如何避免 webview appcelerator 中的远程代码执行?
- c# - 在单声道游戏中从 PNG 图像中删除背景