上午讲了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 '
'.$j.'x'.$i.'='.$j*$i.' | ';
?>

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

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
