【问题标题】:How does this loop work? I am unable to understand it这个循环是如何工作的?我无法理解
【发布时间】:2021-12-15 22:06:45
【问题描述】:
for(int i=1;i<=n;){
    f++;
    if((i++==p) || (i++==p))
        break;
}

例子1:n=7,p=3,f=0;所以f 的值应该是1,对吧?但它给出了f=2 作为输出

示例2:n=7,p=4,f=0;它的输出为f=2

例子3:n=7,p=5,f=0;它的输出为f=3

帮助我理解这一点。

【问题讨论】:

  • 您可能处于未定义的行为领域,在同一个表达式中的同一个变量上有两个后缀运算符实例。
  • 输出对我来说是正确的。在纸上写下你的变量,将手指放在循环中的每个语句上,然后手动运行。每次更新相关变量。请记住,当您使用 postfix-increment (i++) 时,返回的值是 before 被递增的值。
  • @selbie 这似乎不对。 || 的左手操作符必须在右手操作符之前进行评估以启用短路,因此不存在排序歧义。
  • 我正试图找出任何人都可以使用它的地方。它似乎没有多大用处,因为 i 在范围内是本地的。如果 i 被用作字符串的索引,那么if((i++==p) || (i++==p)) 将在中断结束时给出下一个可用位置(如果它不是本地的)。此外,以这种方式递增会违反i&lt;=n,因此很难弄清楚 i 可以有多大。
  • @placidchat -- 你说得对,代码令人困惑,但在循环体中修改循环索引 (i) 本身并没有什么坏处。例如,您可以编写一个 for 循环,而在 for 中没有增量:for (int i =0; i &lt; n; ) { ++i; }。有时这很方便。在这种情况下,由于增量隐藏在 if 语句中的方式,它几乎不可读。

标签: c++ loops for-loop increment


【解决方案1】:

案例 1n=7,p=3,f=0 时。让我们在执行 for 循环时查看不同变量的值。

迭代 1

for(int i=1;i<=n;) //here n = 7
{
   f++; //here f becomes 1 that is now we have f = 1
   if((i++==p) || (i++==p)) // variable i is incremented by 1 and becomes 2 because of the 
   //first i++. But note the old value of i(which is 1) is returned by i++. So although 
   //right now i = 2, its old value(which is 1) is compared with the value of variable 
   //p(which is 3). Since 1 and 3 are not equal the next (i++==p) is evaluated. And so 
   //again variable i is incremented and becomes 3. But here also the old value of 
   //i(which is 2) is used to compare with value of variable p(which is still 3). But since
   //2 is not equal to 3 the control flow doesn't go inside the `if` and so `break` is not 
   //executed.

   break;
}

迭代 2

for(int i=1;i<=n;) //here n = 7
{
   f++; //here f becomes 2 that is now we have f = 2
   if((i++==p) || (i++==p)) // Now i is incremented again because of the first i++ and 
   //becomes 4. But here also the old value of variable i(which is 3) is used to compare 
   //with value of variable p(which is 3) and since 3 = 3 the condition is satisfied 
   //and we go inside the `if` statement and `break` is executed. Note at this point 
   //the value of f is 2 .That is why you get f =2 as output.

   break;
}

类似地,您可以计算案例 2,其中 n=7,p=4,f=0;

请注意,您可以/应该为此目的使用 调试器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-03
    • 2020-08-28
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    相关资源
    最近更新 更多