php - 帕斯卡的三角形有效但抛出了一个通知
问题描述
这是我的脚本。$tri
当我这样做时,程序无法在数组中找到值$somma=$tri[$y]+$tri[$z];
?
我不断收到通知,但为什么呢?
<?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;
}
?>
解决方案
当$y
= $count - 1
,然后$z
=$count
并且永远没有可用的元素 via $tri[$z]
。
例如,在 的第一次迭代中$x
,$tri
是:
array (
0 => 1,
1 => 1,
)
何时一切都很好$y = 0
,$z = 1
但是当嵌套for()
移动到其最终迭代($y = 1
和$z = 2
)时,$tri
没有2
索引。
这就是您收到通知的原因。
使用空合并运算符和其他一些小改动,这似乎运行顺利:
代码:(演示)
$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;
}
或者您可以将一个0
元素推入$tri
内部 for 循环之前并从count()
. https://3v4l.org/sWcrr
推荐阅读
- .htaccess - 如何在 .htaccess 中创建异常?
- java - 带有外部活动 MQ 的 JBoss FUSE 7.4 提供 AMQ219013:等待接收集群拓扑超时。组:空
- python - 如何使用 aiohttp Web 服务器在特定时间发送消息?
- c++ - `std::shared_ptr`的别名构造函数有什么用
- opengl - glReadPixels 可以用来从 GL_TEXTURE_3D 读取图层吗?
- amazon-web-services - 我们可以使用 AWS Data Migration Service 从 Aurora Serverless 作为源进行复制吗?
- c# - 替换完全匹配的字符串
- c++ - 如何在 C++ 中将迭代器作为函数参数传递
- token - 如何仅使用 OAuth 访问令牌将 ibm watson 聊天机器人与 slack 集成
- c++ - MinGW 的“-fno-elide-constructors”的类似物是什么?