審題:
- 水仙花數是一個三位數,所以只要判斷100到999之間即可
- 如何把單個數字拿出來
<做法一>用字符串把單個數字拿出來
package daffodil;
public class DaffodilDemo {
//寫一個方法判斷是否是水仙花數
public void decise() {
//按照順序把這個字符串的數字拿出來,然後把立方後的值加到number裏面
for (int i = 100; i <1000; i++) {
//把number放入循環裏,這樣每次都會清零
int number=0;
//把數字放到字符串,有三種方式
//String str1=""+i;
//String str2=Integer.toString(i);
String str=String.valueOf(i);
for (int j = 0; j < 3; j++) {
number+=Math.pow((Integer.valueOf(str.substring(j, j+1))), 3);
}//for
if(number==i) {
System.out.println(i+"是水仙花數");
}//if
}//for
}//decise
}//DaffodilDemo
package daffodil;
public class Test {
public static void main(String[] args) {
DaffodilDemo dd=new DaffodilDemo();
dd.decise();
}
}
<做法二>用取餘的方式把單個數字拿出來
package daffodil;
public class DaffodilTwo {
public static void main(String[] args) {
int a,b,c;
for (int i = 100; i <1000; i++) {
//拿到百位數
a=i/100;
//兩種方式拿到10位數
// b= i % 100 / 10;
b=i/10%10;
//拿到個位數
c=i%10;
if(a*a*a+b*b*b+c*c*c==i) {
System.out.println(i+"是水仙花數");
}
}
}
}