Home > php教程 > php手册 > body text

for循环连续求和、九九乘法表代码

WBOY
Release: 2016-06-06 20:40:03
Original
1170 people have browsed it

上午讲了PHP的循环语句,for、while、do…while,学过C或者其他语言的对这个应该不陌生了,不过对于新手来说还是有点吃力

for循环的经典例子就是连续求和了:1+2+3+……+100,讲了一个多小时,还是有同学不会。做程序得有思想,有的同学一直敲键盘,也没搞出来。在做这个求和之前,我们要思考一下,求和其实就是连续的累加,当变量$i自增的时候肯定要与之前的数求和,那么怎么与之前的数求和呢?我们可以做一个拆分:把$i之前的数看作一项,单独和$i相加,同理,100加上之前99项的和,99加上之前98项的和……以此类推,2加上之前的数1,那么1呢,就是1+0。在写程序的时候,就是逆向思维了,先算0+1=1,再算1+2=3,接着3+3=6……
代码如下:
/*
*file name: 1+...+100.php
*author: luchanghong
*email: luchanghong@xingmo.com
*time: 2011/5/24
*/
$sum = 0;
$str = '';
for($i = 0 ; $i {
echo $str .= $i.'+';
// echo '
';
// echo $sum.'+'.$i.'=';
echo '=';
echo $sum = $sum+$i;
echo '
';
}
echo $sum;
?>

循环体中间的echo语句是为了测试过程的,可以看的更清晰。
下面的九九乘法表用的是两层for循环,可能新手觉的更难,不过,耐心学习、专心思考还是能看懂的。
代码如下:
/*
*file name: 99.php
*author: luchanghong
*email: luchanghong@xingmo.com
*time: 2011/5/9
*/
echo '';
for($i = 1 ; $i{
echo '';
for($j = 1 ; $j{
echo '';
}
echo '';
}
echo '
'.$j.'x'.$i.'='.$j*$i.'
';
?>
Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!