输出所有的水仙花数
水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。(例如:1^3 + 5^3+ 3^3 = 153)
一个三位数i,取十位上的数字的方法有两种:
1. i%100/10
2. i/10%10
/*
* 输出所有的水仙花数
* v1.0
*/
package com.hongyewell.com;
public class Flower {
public static void main(String[] args){
int i;
for(i=100;i<1000;i++){
int a = i%10; //个位
int b = i%100/10; //十位
int c = i/100; //百位
if(a*a*a+b*b*b+c*c*c==i){
System.out.println("水仙花数:"+i);
}
}
}
}
/*
* 输出所有的水仙花数
* v2.0
* Math.pow(x,y) 计算x的y次方
*/
package com.hongyewell.com;
public class Flower {
public static void main(String[] args){
int i;
for(i=100;i<1000;i++){
int a = i%10; //个位
int b = i%100/10; //十位
int c = i/100; //百位
if(Math.pow(a, 3)+Math.pow(b, 3)+Math.pow(c, 3)==i){
System.out.println("水仙花数:"+i);
}
}
}
}
/*
* 输出所有的水仙花数
* v3.0
* Math.pow(x,y) 计算x的y次方
* Math.pow() 返回结果为double型
* 和int 类型比较的时候 最好强转一下
*/
package com.hongyewell.com;
public class Flower {
public static void main(String[] args){
int i;
for(i=100;i<1000;i++){
int a = i%10; //个位
int b = i%100/10; //十位
int c = i/100; //百位
int j = (int) (Math.pow(a, 3)+Math.pow(b, 3)+Math.pow(c, 3));
if(j==i){
System.out.println("水仙花数:"+i);
}
}
}
}