doupeng5320 2019-03-11 12:10
浏览 35
已采纳

为什么1没有被输出? (简单的php问题)

I have a question which I don't know the answer of. I've been thinking about it for a while.

The following code:

$i = 1;
while($i < 10) 
    if(($i++) % 2 == 0)
    echo $i;

It correctly outputs 3579, but why isnt 1 also included in the output?

I'm a beginner with PHP and am looking forward for someone to help me.

Thank you very much! :D

  • 写回答

1条回答 默认 最新

  • douyou7102 2019-03-11 12:13
    关注

    Two modifications:

    $i = 0; // Make it 0 from 1
    while($i < 10)
    if(($i++) % 2 == 0)
    echo "<br/>".$i; // Make $i instead of $1
    
    Output:
    
    
    1
    3
    5
    7
    9
    

    Program hand run:

    1) Set $i to 0.

    2) If it is greater than 10, go ahead.

    3) Increment it by 1

    4) So, for $i => 0->1, 1->2

    4) if new $i is even, print it. (So for first loop iteration, you are have $i -> 1 instead of 0 because of ++$i

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制