[Java]題目:打印出所有的”水仙花數”

Boom
Jan 15, 2021

--

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>

--

--

Boom
Boom

Written by Boom

Boom Engineer | BOOM ⭐ 程式自學之旅 | 透過筆記釋放記憶體,記錄自己的程式筆記,『內化』成為這段旅程的養分,也分享給路過,正在經歷這趟旅程的你 | Java note begin at 2020.09 | Python note begin at 2021.03

No responses yet