用java写一个n位水仙花数
时间: 2023-04-07 07:01:23 浏览: 137
好的,我可以回答这个问题。以下是用 Java 写一个 n 位水仙花数的代码:
```
import java.util.Scanner;
public class NarcissisticNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入 n 的值:");
int n = input.nextInt();
int start = (int) Math.pow(10, n - 1);
int end = (int) Math.pow(10, n) - 1;
for (int i = start; i <= end; i++) {
int sum = 0;
int temp = i;
while (temp != 0) {
int digit = temp % 10;
sum += Math.pow(digit, n);
temp /= 10;
}
if (sum == i) {
System.out.print(i + " ");
}
}
}
}
```
这个程序可以找出所有 n 位水仙花数并输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)