例子,php打印水仙花数。 代码示例:
php水仙花数函数--www.#function winter($num)
{
if($num<1000){
//定义个位
$ge=$num%10;
//定义十位
$ten=(($num%100)-$ge) /10;
//定义百位
/*floor取整,忽略小数点后面的所有数*/
$hundred=floor($num/100);
$sum1=$ge*$ge*$ge+$ten*$ten*$ten+$hundred*$hundred*$hundred;
if($sum1==$num){
return 1;
} else{
return 0;
}
} else{
return -1;
}
}
if(winter(371)==-1) {
echo "大于1000的数";
}else{
if(winter(371)) {
echo "Yes";
} else{
echo "No";
}
}
?>
例2,php实现水仙花数 代码示例:
for($i=0;$i<1000;$i++)
{
$a=floor($i/100);//求出百位数
$b=floor($i/10)%10;//求出十位数
$c=$i%10;//求出个位数
//if($a*$a*$a+$b*$b*$b+$c*$c*$c==$i)
if(pow($a,3)+pow($b,3)+pow($c,3)==$i)//判断百位、十位
个位的立方和是否等于这个数本身
{
echo $i."
";
}
}
?>