duanlu1793 2018-05-19 21:03
浏览 31
已采纳

使用php打印星形图案时出现意外结果

I am trying to print a star pattern using php. I am trying to print this:

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

my code:

for($i=1; $i<=5; $i++){
    for($j=1; $j<=5; $j++){
        if($j>= (6-$i)){
            echo "*";
        } else {
            echo " ";
        }

    }
    echo "<br>";
}

by doing this I should get above pattern but instead, I am getting this:

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

Anybody can tell me why this is happening? Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dtd14883 2018-05-19 21:15
    关注

    Extra whitespace characters in HTML documents have no effect on the rendered output. If you look at the output page source, you will see that you are getting the correct result. Here are your options:

    1) Send a Content-Type: text/plain header:

    header('Content-Type: text/plain');
    

    Make sure to change your <br> tags to newline characters (" ", " ", or PHP_EOL)

    2) Wrap what you have there with a <pre> tag

    echo '<pre>';
    for($i=1; $i<=5; $i++){
        for($j=1; $j<=5; $j++){
            if($j>= (6-$i)){
                echo "*";
            } else {
                echo " ";
            }
    
        }
        echo "<br>";
    }
    echo '</pre>';
    

    3) Use non-breaking spaces:

    for($i=1; $i<=5; $i++){
        for($j=1; $j<=5; $j++){
            if($j>= (6-$i)){
                echo "*";
            } else {
                echo "&nbsp;";
            }
    
        }
        echo "<br>";
    }
    

    On another note, here's a one-liner that will do the same thing as what you're trying to do without the additional for loop and if/else statements:

    for ($i=1; $i<=5; $i++) {
        echo str_pad(str_repeat('*', $i), 5, ' ', STR_PAD_LEFT) . PHP_EOL;
    }
    

    Try it on 3v4l.org.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了