如何使用php创建金字塔? [英] How can I create a pyramid from using php?

查看:110
本文介绍了如何使用php创建金字塔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用星号创建一个金字塔.我指定一个值,该值将成为金字塔的基础.基数包含与指定值一样多的星号,并且金字塔必须将其行跳过1.在这里,当我指定偶数个基数时,我面临一个问题.

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 pyramid must skip its rows by 1..Here I am facing a problem when I specify an even number of base..

金字塔必须看起来像下面的金字塔.

The pyramid must looke like the one below.

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

我得到

####* 
###*** 
##***** 
###***** 
####***** 
********** 

我想用一些空格替换#,并得到第4行星号数量减少的错误.如何解决这两个错误?

I want to replace the # by some blank space and I am getting the bug that the number of asterisks in the 4th row has decreased.. How do I fix these two bugs ?

function create_pyramid($limit){

     if ($limit > 0){
        for ($row =0;$row<=$limit;$row++){
            if (($row % 2 == 0) && ($row != $limit)){ continue;}
            $rows = "";
            for ($col =0;$col<$row;$col++){
                $rows= $rows.'*';
            }
            $pattern = "%'#".((($limit - $row)/2)+$row)."s\n";
            printf ($pattern,$rows);
            print '<br />';
        }
        }
        else{
            print "Invalid data";
        }
     }

     create_pyramid(10);

推荐答案

只需使其更简单:

function create_pyramid($limit) {
    for($row = 1; $row < $limit; $row ++) {
        $stars = str_repeat('*', ($row - 1) * 2 + 1);
        $space = str_repeat(' ', $limit - $row);
        echo $space . $stars . '<br/>';
    }
}
echo "<pre>" ;
create_pyramid(10);

这篇关于如何使用php创建金字塔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆