使用Java写一个判断水仙花数程序
时间: 2024-05-11 21:16:30 浏览: 6
好的,以下是Java语言实现判断水仙花数的程序:
```
import java.util.Scanner;
public class NarcissisticNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个三位数:");
int num = input.nextInt();
int units = num % 10;
int tens = num / 10 % 10;
int hundreds = num / 100;
if (num == units * units * units + tens * tens * tens + hundreds * hundreds * hundreds) {
System.out.println(num + "是水仙花数!");
} else {
System.out.println(num + "不是水仙花数!");
}
}
}
```
上面的程序中,我们首先从控制台输入一个三位数,然后将其百位、十位和个位分别取出来,分别赋值给 `hundreds`,`tens` 和 `units` 三个变量。接着,我们判断这个数是否等于它的各位数字的立方和。如果等于,就输出它是水仙花数;否则输出它不是水仙花数。
希望这个程序对你有帮助!