水仙花数练习

该博客展示了如何使用for循环和while循环在Java中找出并打印所有三位数的水仙花数,同时统计其数量。水仙花数是指各位数字立方和等于该数本身的三位数,如153。通过循环遍历100到999之间的数字,检查是否满足水仙花数条件,最终得出共有4个水仙花数。
摘要由CSDN通过智能技术生成

for循环语句

package com.test;
public class Test {
    public static void main(String[] args) {
        //需求:在控制台输出所有的”水仙花数”
        //需求:统计”水仙花数”共有多少个
        //所谓的水仙花数是指一个三位数,其各位数字的立方和等于该数本身。
        //举例:153就是一个水仙花数。153 = 1*1*1 + 5*5*5 + 3*3*3 = 153
        int count = 0; //记录水仙花数
        for (int i = 100; i < 1000; i++) {
            int a = i / 100; //百位
            int b = i / 10 % 10; //十位
            int c = i % 10; //个位
            if (i == a*a*a + b*b*b + c*c*c){
                count++;
                System.out.println(i); //153 370 371 407
            }
        }
        System.out.println("有" + count + "个水仙花数"); //有4个水仙花数
    }
}

while循环语句

package com.test;
public class Test {
    public static void main(String[] args) {
        //需求:在控制台输出所有的”水仙花数”
        //需求:统计”水仙花数”共有多少个
        //所谓的水仙花数是指一个三位数,其各位数字的立方和等于该数本身。
        //举例:153就是一个水仙花数。153 = 1*1*1 + 5*5*5 + 3*3*3 = 153
        int num = 100; //初始化的值
        int count = 0; 记录水仙花数
        while (num >= 100 && num <= 999){
            int a = num / 100; //百位
            int b = num / 10 % 10; //十位
            int c = num % 10; //个位
            if (num == a*a*a + b*b*b + c*c*c) {
                count++;
                System.out.println(num); //153 370 371 407
            }
            num++;
        }
        System.out.println("有" + count + "个水仙花数"); //有4个水仙花数
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值