How can I create a pyramid from using php?

前端 未结 14 1253
耶瑟儿~
耶瑟儿~ 2020-12-11 08:58

I need to create a pyramid using asterisks. I specify a value which becomes the base of the pyramid. The base contains as much asterisks as the value specified and the pyram

14条回答
  •  孤城傲影
    2020-12-11 09:27

    I prefer mine :

      echo '
    ';
    
      $n = 5;
      function print_tree($n, $str, $max) {
        for ($i = 0; ($i < (($max - $n) / 2)); $i++) {
          echo " ";
        }
        for ($i = 0; ($i < $n); $i++) {
          echo $str;
        }
        echo "
    "; } for ($flag = 0; ($flag < 2); $flag++) { for ($a = 1, $b = 1, $c = 1, $d = 4; (($d - 3) <= $n); $a += 2, $b++) { if ($flag == 1) { print_tree($a, "*", $max); } if ($b == $d) { if ($flag == 0) { $max = $a; } if (($d - 3) != $n) { $a -= ((2 * $c) + 2); } $b = 0; $d++; if (($d % 2) == 0) { $c++; } } } } if ((($foot = $n) % 2) == 0) { $foot++; } for ($i = 0; ($i < $foot); $i++) { print_tree($foot, "|", $max); }

    outputs :

                       *
                      ***
                     *****
                    *******
                     *****
                    *******
                   *********
                  ***********
                 *************
                  ***********
                 *************
                ***************
               *****************
              *******************
             *********************
               *****************
              *******************
             *********************
            ***********************
           *************************
          ***************************
         *****************************
           *************************
          ***************************
         *****************************
        *******************************
       *********************************
      ***********************************
     *************************************
    ***************************************
                     |||||
                     |||||
                     |||||
                     |||||
                     |||||
    

    Or even this one:

    it gives:

                   *
                  ***
                 *****
                *******
               *********
              ***********
             *************
            ***************
           *               *
          ***             ***
         *****           *****
        *******         *******
       *********       *********
      ***********     ***********
     *************   *************
    *************** ***************
    

    funny exercices isn't it... 8-)

提交回复
热议问题