題目:輸出所有的“水仙花數”。所謂“水仙花數”是指一個3位數,其各位數字立方和等於該數的本身。例如,153就是一個水仙花數,因為153=13+53+33。
代碼實現如下:
在線測試
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
document.write("水仙花數有:");
for(var i=100;i<1000;i++)
{
var a=i%10;//提取個位數
var b=(i/10)%10 //提取十位數
b=parseInt(b);
var c=i/100;//提取百位數
c=parseInt(c);
if(i==(a*a*a+b*b*b+c*c*c))
{
document.write(i+",");
}
}
</script>
</head>
<body>
</body>
</html>
在浏覽器預覽效果如下:
分析:
parseInt()函數是將一個數轉換為整型數據,我們在“JavaScript類型轉換”這一節中已經詳細給大家講解了。