java打印水仙花数

题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。

具体代码:

public class Flower{
    public static void main(String[] args){
        int sum=0;//水仙花总数
        for(int i=100;i<1000;i++){
            int bite=i%10;//获得个位数
            int ten=i/10%10;//获得十位数
            int hundered=i/100;//获得百位数
            //打印符合条件的数字
            if(i==(bite*bite*bite)+(ten*ten*ten)+(hundered*hundered*hundered)){
                System.out.print(i+"    ");
                sum++;
            }
            
        }
        System.out.println("总共有水仙花个数"+sum);
    }
}

猜你喜欢

转载自www.cnblogs.com/yanpingping/p/10507006.html