综合百科

java实现水仙花数的计算

看到标题java实现水仙花数,首先先要知道什么是水仙花数,具体了解一下

所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数

列如153=1*1*1+5*5*5+3*3*3 那么153就是水仙花数,首先是分析需要的功能,首先他是一个3位数。

那值一定在100-1000之间,必定要用到循环。可用for循环,while循环,do while 循环,其次是它需要满足条件

“其各位数字立方和等于该数”,那么我们必须把他的各位的数字取出。我们在循环里做判断,当数满足条件就将这个数取出。

那么可做出如下流程图。

根据流程图,可得如下代码。代码几种循环的方法都用的了。

package com.tjgx.lxb;/*要求:100--1000的水仙花数 * 水仙花定义:水仙花数”是指一个三位数,其各位数字立方和等于该数 * **/public class Daffodils { public static void main(String[] args) { System.out.println("用dowhile循环方法"); demo1(); System.out.println("用for循环方法"); demo2(); System.out.println("用while循环方法"); demo3();   }  //用dowhile 循环来做public static void demo1() { int i=100; do{ int g=i%10; //取出个位数 int s=i/10%10; //取出十位数 int b=i/100; //取出百位数 if(g*g*g+s*s*s+b*b*b==i) { System.out.println(i+"是水仙花数"); }  i++;  }while(i<1000); } //用for循环来做public static void demo2() { for(int j=100;j<1000;j++) { int g=j%10; //取出个位数 int s=j/10%10; //取出十位数 int b=j/100; //取出百位数 if(g*g*g+s*s*s+b*b*b==j) { System.out.println(j+"是水仙花数"); }  } }//用while循环来做public static void demo3() { int k=100; while(k<1000) { int g=k%10; //取出个位数 int s=k/10%10; //取出十位数 int b=k/100; //取出百位数 if(g*g*g+s*s*s+b*b*b==k) { System.out.println(k+"是水仙花数"); }  k++;  } } }

运行结果如下图