JS输出水仙花数for循环和while循环实现

短命女 2021-09-15 15:22 649阅读 0赞

输出所有的水仙花数,水仙花数:各个位数立方和等于这个数的三位数,

//算次方的方法:Math.pow(m,n); ->m的n次方

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>水仙花数</title>
  6. </head>
  7. <body>
  8. </body>
  9. <script>
  10. //练习:输出所有的水仙花数,水仙花数:各个位数立方和等于这个数的三位数,
  11. //算次方的方法:Math.pow(m,n); ->m的n次方
  12. for(var i=100;i<=999;i++){
  13. //获得本次循环i的个位,十位,百位
  14. var bai=parseInt(i/100);
  15. var shi=parseInt(i%100/10);
  16. var ge=parseInt(i%10);
  17. if(i==Math.pow(bai,3)+Math.pow(shi,3)+Math.pow(ge,3)){
  18. document.write(i+"<br>");
  19. }
  20. }
  21. var i = 100;
  22. while(i<=999){
  23. var bai=parseInt(i/100);
  24. var shi=parseInt(i%100/10);
  25. var ge=parseInt(i%10);
  26. if(i==Math.pow(bai,3)+Math.pow(shi,3)+Math.pow(ge,3)){
  27. document.write(i+"<br>");
  28. }
  29. i++;
  30. }
  31. </script>
  32. </html>

发表评论

表情:
评论列表 (有 0 条评论,649人围观)

还没有评论,来说两句吧...

相关阅读