循环嵌套--水仙花

本文介绍了如何使用Java编程实现寻找和判断水仙花数的方法。通过两个程序示例,分别展示了遍历1到999输出所有水仙花数,以及输入一个三位数判断其是否为水仙花数的逻辑。主要涉及循环和条件判断语句的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:在控制台输出所有的”水仙花数”
	* 所谓的水仙花数是指一个三位数,其各位数字的立方和等于该数本身。
class Demo7 
{
	public static void main(String[] args) 
	{
		int i=1;
	    int sum=0;
	    while(i<=100){
	        sum+=i++;//等同于sum+=i;i++;
	    }
	    System.out.println(sum);
		int j=100;
		int a=0,b=0,c=0,count=0;
		while(j<=999){
		   a=(j/100)%10;//可求任意位数的个十百位
		   b=(j%100)/10;
		   c=j%10;
		   if(a*a*a+b*b*b+c*c*c==j){
		      count+=1;
		   }
		   j++;
		}
		System.out.println("水仙花数为:"+count);


	}
}
需求:输入一个三位数,判断它是否为水仙花数
import java.util.Scanner;
class test 
{
	public static void main(String[] args) 
	{
		Scanner sc=new Scanner(System.in);
		int i=sc.nextInt();
		int a=0,b=0,c=0;
		if(100>i || i>=1000){
			System.out.println("输入错误");
		}else{		  
		   a=(i/100)%10;//可求任意位数的个十百位
		   b=(i%100)/10;
		   c=i%10;
		   if(a*a*a+b*b*b+c*c*c==i){
		      System.out.println(i+"为水仙花数"); 
		   }else{
			    System.out.println(i+"不是水仙花数");
		   }	  
		}
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值