c++ - 为什么一行输出(在 while 循环中)使不变量为假?

标签 c++ while-loop

我试图更深入地理解 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 = 输出中的行数”。

--------------------什么是不变量----------------

What is an invariant?

最佳答案

基本上,您在评论中回答了自己的问题:

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/

相关文章:

Java Clock 模拟,不知道如何进行 do...while

java - 跳过 while 循环的第一行

python - 如何让 for 循环在 while 循环的每次迭代中重新评估

c - 如何格式化代码以便触发 while 循环 C

python - 为什么 while 循环中的缩进会产生问题?

c++ - 从所有列出的文件和子目录更改目录

c++ - 它是如何工作的,如何使用宏编译 TCL 的 C++ 扩展而没有主要功能

c++ - 从 C++ 列表中删除对象

c++ - freopen_s ("conout$") 和 fclose

c++ - 为什么在增强或标准中没有 "variant"?