public class ex3 {
public static void main(String[] args) {
/*
題目:打印出所有的”水仙花數”,所謂”水仙花數”是指一個三位數,
其各位數字立方和等於該數本身。例如:153是一個”水仙花數”,
因為153=1的三次方+5的三次方+3的三次方。
ANS:
主程式:
取出百位、十位、個位數,印出所有水仙花數
副程式:
判斷是否為「水仙花數」
*/
int hun,ten,di;//百、十、個
for(int i=101;i<1000;i++)
{
hun=i/100;
ten=(i%100)/10;//十位
di=i%10;//個位
if(isFlower(i,hun,ten,di))
{
System.out.printf(“%d\t”,i);
}
}
}
private static boolean isFlower(int i,int hun,int ten,int di)
{
int sum;
//因為Math.pow預設跑出來的資料型態是double
sum=(int) (Math.pow(hun,3)+Math.pow(ten,3)+Math.pow(di,3));
if(i==sum)
return true;
else
{
return false;
}
}
}
<console>