duanmiao6695 2018-10-13 15:20
浏览 58
已采纳

帕斯卡的三角形有效,但会发出通知

Here is my script. The program can't find values in $tri array when I do $somma=$tri[$y]+$tri[$z];?

I keep getting Notices, but why?

<?php
$tri=array(1,1);
for ($x=0;$x<=6;$x++) {
    print_r($tri);
    $count=count($tri);
    $trinew=array();
    for($y=0;$y<$count;$y++) {
        $z=$y+1;
        $somma=$tri[$y]+$tri[$z];    // <-- here is the problem
        array_push($trinew,$somma);
    }
    array_unshift($trinew, 1);
    $tri=$trinew;
}
?>
  • 写回答

1条回答 默认 最新

  • donglian7879 2018-10-13 15:46
    关注

    When $y = $count - 1, then $z = $count and there is never an element available via $tri[$z].

    For example, on the first iteration of $x, $tri is:

    array (
      0 => 1,
      1 => 1,
    )
    

    When $y = 0 and $z = 1 everything is fine, but when the nested for() moves to its final iteration ($y = 1 and $z = 2), $tri doesn't have a 2 index.

    This is why you are receiving Notices.


    With a null coalescing operator and some other minor touches, this seems to run smoothly:

    Code: (Demo)

    $tri = [1, 1];
    for ($x = 0; $x <= 6; ++$x) {
        var_export($tri);
        $trinew = [1];
        for($y = 0, $count = count($tri); $y < $count; ++$y) {
            $z = $y + 1;
            $trinew[] = $tri[$y]  + ($tri[$z] ?? 0);
        }
        $tri = $trinew;
    }
    

    Or you could push a 0 element into $tri before the inner for loop and subtract 1 from the count(). https://3v4l.org/sWcrr

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

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端