1. 程式人生 > >java基礎--do..while迴圈實現水仙花數

java基礎--do..while迴圈實現水仙花數

什麼是水仙花數

解析:

一個三位數,其各位數字的立方和是其本身
例如:
153 = 1*1*1+5*5*5+3*3*3
使用for迴圈
問題:
如何獲取各位的數?
例如:
153--
個位3: 153 % 10       =3
十位5: 153 /10 %10     =5
百位1: 153 /10 /10 %10  =1

上程式碼:

package com.lcn.day04;

public class NarcissisticNumberDemo1 {

	/**
	 * do..while迴圈實現水仙花數問題
	 */
	public static void main(String[] args) {
		System.out.println("100-999中的水仙花數有:");
      
		int i = 100;       //1-初始化變數
		do{
//------------------------------------------------------------------			
			int ge = i%10;       //得到個位
			int shi = i/10%10;   //得到十位
			int bai = i/100%10;   //得到百位           //3-迴圈體語句
			if((ge*ge*ge+shi*shi*shi+bai*bai*bai) == i){
				System.out.println(i);
//------------------------------------------------------------------				
			}
			i++;    //4-控制條件語句
		}while(i<1000);  // 判斷條件語句

	}

}
輸出:

100-999中的水仙花數有:

153
370
371
407