dongmi5020 2018-05-29 18:04
浏览 83
已采纳

考试Qn:将while while循环转换为for循环(PHP)

Recently, my exams got over. My last exam was based on PHP. I got the following question for my exam:

"Convert the following script using for loop without affecting the output:-"

<?php
 //Convert into for loop
 $x = 0;
 $count = 10;
 do
 {
  echo ($count. "<BR>");
  $count = $count - 2;
  $x = $x + $count; 
 }
 while($count < 1)
 echo ($x);
?>

Please help me as my computer sir is out of station and I am really puzzled by it.

  • 写回答

2条回答 默认 最新

  • doulao5916 2018-05-29 18:15
    关注

    Well, If I understand well, You have to use "for" loop, instead of "do...while", but the printed text must not change.

    Try:

    $count = 10;
    $x = 0;
    $firstRun = true;
    for(; $count > 1 || $firstRun;) {
        $firstRun = false;
        echo ($count . "<BR>");
        $count -= 2;
        $x = $x + $count; 
    }
    echo ($x);
    

    By the way loop is unnecessary, because $count will be greater than 1 after the first loop, so the while will get false.

    EDIT

    • $firstRun to avoid infiniteLoop
    • $count in loop

    EDIT

    • Fixed code for new requirement
    • Removed unnecessary code
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化