教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php打印杨辉三角综合实例

php打印杨辉三角综合实例

发布时间:2018-04-02   编辑:jiaochengji.com
本文介绍了php打印杨辉三角的一个例子,用php实现输出杨辉三角的方法,有需要的朋友参考下。

例子,php打印杨辉三角。
 

复制代码 代码示例:

<?php 
$params=getParams(1); 
$argv0=trim($params[0]); 
 
if(!is_numeric($argv0)) 

    error_msg("params 1 must be a numbers"); 

$spaceNumber=6; 
$maxn=$argv0; 
 
output("",true); 
get_trangle($argv0); 
error_msg("execute success"); 
 
function get_trangle($n){ 
    if($n <= 0) 
    {  // www.jbxue.com
         
        return false; 
    } 
    if($n==1) 
    { 
            $this_level=array(1); 
            print_line($this_level,$n); 
            return array(1); 
    } 
    if($n==2) 
    { 
            $this_level=array(1,1); 
            print_line(array(1),1); 
            print_line($this_level,$n); 
            return $this_level; 
    } 
    $last_level=get_trangle($n-1); 
    if(!is_array($last_level)||count($last_level) < 2) 
    { 
        
        return false; 
    } 
    $this_level=array(); 
    $this_level[0]=1; 
    
    for($i=0;$i< count($last_level)-1;$i++) 
    { 
        $this_level[$i+1]=$last_level[$i]+$last_level[$i+1]; 
    } 
    $this_level[]=1; 
    print_line($this_level,$n); 
    return $this_level; 

 
function print_line($aArray,$n) 

    global $maxn,$spaceNumber; 
    $line=sprintf("%".(($maxn-$n)*$spaceNumber/2)."s","");   
    foreach($aArray as $i)  
    { 
        $line.=sprintf("%".$spaceNumber."s",$i); 
    } 
    output($line); 

 
function getParams($paramNum) 

    $in=file_get_contents("in.txt"); 
    if($in===FALSE){ 
        error_msg("cannot read in.txt,please check in.txt exists\n");    
    } 
    $in=preg_replace("/(\s+)/i", " ", $in); 
    
    $parms=split(" ",trim($in)); 
    if($parms===FALSE) 
    { 
        error_msg("cannot get param from in.txt\n"); 
    } 
    if(count($parms) < $paramNum) 
    { 
        error_msg("it needs $paramNum params\n"); 
    } 
    return $parms; 

//输出 杨辉三角
function output($msg,$isClean=false) 

    if($isClean) 
    { 
    $handle = fopen('out.txt', 'w'); 
    fclose($handle);     
    } 
    error_log($msg."\n", 3, "out.txt"); 

 
function error_msg($msg,$is_exit=true) 

    if($is_exit) 
        die($msg."\n"); 
    else
        echo $msg."\n"; 

?>

您可能感兴趣的文章:
PHP打印杨辉三角二种方法
PHP打印杨辉三角图文教程
php打印杨辉三角小例子
php打印杨辉三角综合实例
PHP实现杨辉三角示例
php杨辉三角简单实例
javascript杨辉三角的例子
用PHP实现杨辉三角的例子
杨辉三角批处理打印脚本
JavaScript代码求杨辉三角给定行的最大值

关键词: 杨辉三角   
[关闭]
~ ~