PHP 用二维矩阵生成一个给定层数的杨辉(PASCAL)三角形
跳至
[3]
[全屏预览]
<meta charset="utf-8"> <title>杨辉三角形 Pascal Triangle</title> <?php if ($_POST['button']){ //定义未来三角形的层数为常数 N define("N",$_POST['number']); //首先,把用来显示三角形的2维矩阵(2N*(N+1))的每个元素清理成零 for($i=0;$i<N+1;$i++) for($j=0;$j<2*N;$j++) $a[$i][$j]= 0; $a[0][N]=1; //再将矩阵第一行中间位置的元素, 赋以 1 /* 这样一来,杨辉三角形的形成规律便是:从第二行开始, * 每一个显示数字的元素,其数字的数值是, * 它头顶元素的左边邻居的数值, * 与它头顶元素的右边邻居的数值之和。 * 据此,给有关元素赋于相应的值。 */ for ($i=1;$i<N;$i++) //从第二层开始赋值: $i=1; for ($j=1;$j<2*N;$j++) //按上述规律,求左上角元素数值,与右上角元素数值之和 $a[$i][$j]=$a[$i-1][$j-1]+$a[$i-1][$j+1]; // 打印输出建成的矩阵 echo '你要求建立的'.N.'层杨辉三角形如下:'.'<table>'; for($i=0;$i<N;$i++){ echo '<tr>'; for($j=0;$j<2*N+1;$j++){ echo '<td width="35" height="15"><center>'; if ($a[$i][$j] !=0) //只打印不为零的数字 echo $a[$i][$j];//只打印不为零的数字, echo '</center></td>'; } echo '</tr>'; } echo '</table>'; echo '<br><a href="pascal.php">返回</a>'; }else{ ?> <form action="pascal.php" method="post"> 输入层数: <input type="number" name="number"> <input type="submit" name="button" value="提交(最多12层)"> </form> <?php } ?>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article
Assassin's Creed Shadows: Seashell Riddle Solution
3 weeks ago
By DDD
What's New in Windows 11 KB5054979 & How to Fix Update Issues
2 weeks ago
By DDD
Where to find the Crane Control Keycard in Atomfall
3 weeks ago
By DDD
Assassin's Creed Shadows - How To Find The Blacksmith And Unlock Weapon And Armour Customisation
4 weeks ago
By DDD
Roblox: Dead Rails - How To Complete Every Challenge
3 weeks ago
By DDD

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics
CakePHP Tutorial
1386
52

