【问题标题】:need understanding of while loop condition (see comment)需要了解 while 循环条件(见评论)
【发布时间】:2012-03-16 15:53:12
【问题描述】:
while (x >= 1000)
{
    cout << "M";
    x -= 1000;
}

有人可以向我解释一下这个 while 循环是如何工作的吗?我知道条件是 x 大于或等于 1000,它会打印出 'M'。

后面的部分是我其实不明白的,是说它会一直从X中减去一千并一直打印直到条件为假?

【问题讨论】:

  • 欢迎来到 Stack Overflow!请记住,赞赏是通过投票和接受的答案(复选标记)来表示的。如果您有任何问题,FAQ 是一个很好的资源,尤其是关于如何提问的部分FAQ
  • 当你得到答案时,给好的答案点赞,接受最好的!欢迎来到 SO

标签: c++ while-loop


【解决方案1】:

是的,这正是它要做的。

这大致翻译为:

当 x 大于或等于 1000 时,执行代码块中的操作(一遍又一遍,直到条件失败)

然后代码块打印 M 并设置 x 等于它自己减去 1000。(x -= 1000x = x - 1000 相同

假设:

x = 3000
x is greater than 1000
print M
x is set to 2000
loop resets and checks x...passes test
print M
x is set to 1000
loop resets and checks x...passes test because of = portion
print M
x is set to 0
loop resets and checks x...fails
moves to the code after the while code block

【讨论】:

    【解决方案2】:
    while (x >= 1000)   //x is greater than or equal to 1000
    {                   //executes loop if condition true, else the statement after the loop block
        cout << "M";  // print M
        x -= 1000;    // x = x-1000
    }                  //goes back to condition checking
    

    【讨论】:

      【解决方案3】:

      你是对的!

      x-=1000; 
      

      其实是

      x=x-1000;
      

      【讨论】:

        【解决方案4】:

        是的。

        它说它将继续从 X 中减去一千并继续打印直到条件为假

        【讨论】:

          【解决方案5】:

          该程序似乎是一种低效的编写方式

          x %= 1000;
          

          x = x%1000,其中% 是取模运算符。

          您的代码通过后续减法达到相同的结果,并在 x&lt;1000 时停止。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-06-23
            • 2013-10-29
            • 1970-01-01
            • 1970-01-01
            • 2023-03-25
            • 2019-09-18
            相关资源
            最近更新 更多