Home php教程 PHP源码 PHP 用二维矩阵生成一个给定层数的杨辉(PASCAL)三角形

PHP 用二维矩阵生成一个给定层数的杨辉(PASCAL)三角形

Jun 02, 2016 am 09:14 AM

跳至 [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

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)