dongsuo0517 2015-11-30 01:06
浏览 8
已采纳

棘手的循环代码

I have this simple code but I don't understand why the output is '234567' instead of '246'.

$a = 1;
while ($a < 10)
{
  echo $a+1;
  if ($a == 6)
  {
   break;
 }
 $a += 1;
}



Output:

234567
  • 写回答

1条回答 默认 最新

  • dongpu2476 2015-11-30 01:13
    关注

    Because in the 4th line you are printing the result of ($a + 1) but you are NOT adding 1 to the variable $a.

    Trace 1:

    $a = 1
    
    echo 1+1; // ($a + 1) 2. PRINTS two but $a is still 1
    $a = $a + 1; // now $a is equal to 2 ( 1 + 1 )
    // Current output 2
    

    Trace 2:

    $a = 2 // from trace 1
    
    echo 2+1; // ($a + 1) 3. PRINTS 3 but $a is still 2
    $a = $a + 1; // now $a is equal to 3 ( 2 + 1 )
    // Current output 23
    

    Trace 3:

    $a = 3 // from trace 2
    
    echo 3+1; // ($a + 1) 4. PRINTS 4 but $a is still 3
    $a = $a + 1; // now $a is equal to 4 ( 3 + 1 )
    // Current output 234
    

    And so on.

    To do what you wanted:

    $a = 1;
    while ($a < 10)
    {
        echo ++$a;
    
        if ($a == 6) break;
    
        $a += 1;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示