第一种方式:
package test; public class Exsercise { public static void main(String[] args) { int sum; System.out.println("100~999之间的水仙花数为:"); for (int i = 100; i <= 999; i++) { sum = getCubic(i/100) + getCubic((i/10)%10) + getCubic(i%10); if(sum == i){ System.out.print(i + " "); } } } public static int getCubic(int num){ num = num * num * num; return num; } }
结果视图:
第二种方式:while语句
package test; public class Exsercise { public static void main(String[] args) { int sum; int i = 100; System.out.println("100~999之间的水仙花数为:"); while(i < 1000){ sum = getCubic(i/100) + getCubic((i/10)%10) + getCubic(i%10); if (sum == i) { System.out.print(i + " "); } i++; } } public static int getCubic(int num){ num = num * num * num; return num; } }
结果视图:
第三种方式:do……while语句:
package test; public class Exsercise { public static void main(String[] args) { int sum; int i = 100; System.out.println("100~999之间的水仙花数为:"); do{ sum = getCubic(i/100) + getCubic((i/10)%10) + getCubic(i%10); if (sum == i) { System.out.print(i + " "); } i++; }while(i<1000); } public static int getCubic(int num){ num = num * num * num; return num; } }
结果展示:
好了,欢迎优化改进!