Php 如何使用n输入实现此数字模式
我想输入n,得到这样的模式 模式如果n=4Php 如何使用n输入实现此数字模式,php,Php,我想输入n,得到这样的模式 模式如果n=4 1 222 33333 4444444 33333 222 1 $n=4; $output = str_repeat("$n", (2*$n)-1).PHP_EOL; for ( $i = $n-1; $i>0; $i-- ) { $line = str_repeat(' ', $n-$i).str_repeat("$i", (2*$i)-1); $output = $line.PHP_EO
1
222
33333
4444444
33333
222
1
$n=4;
$output = str_repeat("$n", (2*$n)-1).PHP_EOL;
for ( $i = $n-1; $i>0; $i-- ) {
$line = str_repeat(' ', $n-$i).str_repeat("$i", (2*$i)-1);
$output = $line.PHP_EOL.$output.$line.PHP_EOL;
}
echo $output;
实现这一目标的最佳方式是什么
我试过了。但是我的代码不好!有没有办法用更少、更清晰的代码来实现这一点
echo '<pre>';
$n=4;
for ($i=1; $i <= $n*2-1; $i++) {
if($n<$i){ //bottom part
$scount=$i-$n;
$iterator = 0;
while($iterator != $scount){
$iterator++;
echo ' ';
}
$num = ($n*2)-$i;
$loop = $num*2-1;
$iterator = 0;
while($iterator != $loop){
$iterator++;
echo $num;
}
}elseif ($n==$i){ // middle part
$loop = $i*2-1;
$iterator = 0;
while ($iterator != $loop) {
$iterator++;
echo $i;
}
}else{ //top part
$scount = $n-$i;
$iterator=0;
while ($iterator != $scount) {
$iterator++;
echo ' ';
}
$loop = $i*2-1;
$iterator = 0;
while($iterator != $loop){
$iterator++;
echo $i;
}
}
echo "<br>";
}
?>````
<pre>
1
222
33333
4444444
33333
222
1
</pre>
echo';
$n=4;
对于($i=1;$i)````
你可以通过注意到最长的一行是最大值为n的那一行,其中有2*n-1
n个。所有其他行都需要间隔,使它们与该行上的n个数与最长行上的n个数之差的一半对齐。这是生成这些重复的好方法非对称字符串:
echo“\n”;
$n=4;
$max_length=$n*2-1;
for($i=1;$iTwo for循环重复所需的空格数和字符数
$n=4;
对于($i=1;$i0;$i--){
回声重复序列(“,$n-$i+1)。重复序列($i,$i*2-1)。“\n”;
}
在与其他答案类似的行上,但这将使用输出构建一个字符串。这允许它构建循环中的每个重复行,并将其添加到结果字符串的开头和结尾。这意味着循环仅运行$n-1
次(加上设置中间行的第一行)
感谢您的时间和快速回复!非常感谢!感谢您的时间和代码的魅力!我非常感谢!@kaushick理论上这是最有效的code@Andreas是的
$n = 4;
for($i=1;$i<=$n;$i++){
echo str_repeat(" ", $n-$i+1) . str_repeat($i, $i*2-1) . "\n";
}
for($i=$n-1;$i>0;$i--){
echo str_repeat(" ", $n-$i+1) . str_repeat($i, $i*2-1) . "\n";
}
$n=4;
$output = str_repeat("$n", (2*$n)-1).PHP_EOL;
for ( $i = $n-1; $i>0; $i-- ) {
$line = str_repeat(' ', $n-$i).str_repeat("$i", (2*$i)-1);
$output = $line.PHP_EOL.$output.$line.PHP_EOL;
}
echo $output;