【JAVA】输出所有水仙花数(如果一个3位正整数的各个位数立方和等于这个数本身,称为水仙花数)。

Java实现水仙花数
本文介绍了如何使用Java编程找出所有的3位水仙花数,即各位数字立方和等于其本身的3位正整数。

class Daffodil{
	
	public static void main(String args[]){
		int s = 0;
		int t,c;
		for(int i=100; i<=999; i++){
			c = i;
			for(int j=0; j<3; j++){
				t = c % 10;
				c = c / 10;
				s += t*t*t;				
			}				
			if(s == i){
				System.out.println(i);
			}
			s = 0;
				
		}		
	}	
}

输出结果:
在这里插入图片描述

以下几种 Java 代码实现可用于判定一个三位正整数是否为水仙花: #### 方法一:基础实现 ```java import java.util.Scanner; public class NarcissisticNumberBasic { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入一个三位:"); int n = sc.nextInt(); int j1 = n / 100; int j2 = (n - (j1 * 100)) / 10; int j3 = (n - (j1 * 100 + j2 * 10)); if (j1 * j1 * j1 + j2 * j2 * j2 + j3 * j3 * j3 == n) { System.out.println(n + "是一个水仙花"); } else { System.out.println(n + "不是一个水仙花"); } } } ``` 此方法先获取用户输入的三位,接着分离出百、十个位数字,再计算各数字立方,最后比较立方与原是否相等来判断是否为水仙花[^1]。 #### 方法二:增加输入范围判断 ```java import java.util.Scanner; public class NarcissisticNumberRangeCheck { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入一个三位:"); int i = sc.nextInt(); if (i < 100 || i > 999) { System.out.println(i + "不是一个三位"); } else { int a = i / 100; int b = i / 10 % 10; int c = i % 10; if (a * a * a + b * b * b + c * c * c == i) { System.out.println(i + "是水仙花"); } else { System.out.println(i + "不是水仙花"); } } } } ``` 该方法在基础上增加了对输入数字是否为三位的判断,若不是三位则直接输出提示信息,若是三位再进行水仙花的判断[^2]。 #### 方法三:使用函封装判断逻辑 ```java import java.util.Scanner; public class NarcissisticNumberFunction { public static boolean isNarcissistic(int num) { int a = num / 100; int b = num / 10 % 10; int c = num % 10; return a * a * a + b * b * b + c * c * c == num; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入一个:"); int i = input.nextInt(); if (isNarcissistic(i)) { System.out.println("这是一个水仙花"); } else { System.out.println("这不是一个水仙花"); } } } ``` 此方法将判断逻辑封装在 `isNarcissistic` 函中,提高了代码的复用性,在 `main` 函中调用该函进行判断[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值