我试图更深入地理解 while 循环。我理解的基础知识是,只要测试条件为真,一段时间就会重复该语句。
在 Accelerated C++ 一书中,作者陈述如下:
//the number of blanks surrounds the greeting
const int pad = 1;
//total number of rows to write
const int rows = pad * 2 + 3;
//we have written r rows so far
int r = 0;
//setting r to 0 makes the invariant true
while (r != rows){
//we can assume that the invariant is true here
//writing a row of output makes the invariant false
std::cout << std::endl;
//incrementing r makes the invariant true again
++r;
}
//we can conclude that the invariant is true here
我不明白,为什么写一行输出不变的 false,然后在递增时再次为 true。这本书的作者是否犯了错误?
编辑 - 该变体只是一种智能工具,可以更轻松地理解 while 循环。在此示例中,变体是“r = 输出中的行数”。
--------------------什么是不变量----------------
最佳答案
基本上,您在评论中回答了自己的问题:
They only said "Writing a row of output causes the invariant to become false, because r is no longer the number of rows we have written. However, incrementing r to account for the row that was written will make the invariant true again."
总结:
- 不变量是“r = 写入输出的行数”
- 打印一个空行会使这个不变量无效(因为 r 没有改变,但是写入输出的行数增加了 1)
- 将 r 递增 1 后,不变量再次为真
关于c++ - 为什么一行输出(在 while 循环中)使不变量为假?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19378209/