java语言求水仙花数
时间: 2023-11-16 07:01:04 浏览: 45
以下是Java语言实现求水仙花数的代码:
```java
public class NarcissisticNumber {
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
int a = i / 100; // 求出百位数
int b = i % 100 / 10; // 求出十位数
int c = i % 10; // 求出个位数
if (a * a * a + b * b * b + c * c * c == i) {
System.out.println(i);
}
}
}
}
```
相关问题
使用Java求水仙花数
以下是使用 Java 语言求解水仙花数的代码:
```java
public class NarcissisticNumber {
public static void main(String[] args) {
int num, sum, temp;
System.out.println("水仙花数有:");
for (int i = 100; i < 1000; i++) {
num = i;
sum = 0;
while (num != 0) {
temp = num % 10;
sum += temp * temp * temp;
num /= 10;
}
if (sum == i) {
System.out.print(i + " ");
}
}
}
}
```
运行结果:
```
水仙花数有:
153 370 371 407
```
代码中,我们使用 for 循环遍历 100 到 999 之间的所有三位数,然后将每个数的各位数字的立方和计算出来,最后判断是否等于该数本身,如果是,则输出该数,否则继续循环。
用java语言实现遍历水仙花数
/**
* 遍历水仙花数
*/
public class NarcissisticNumber {
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
int a = i / 100; // 获取百位数
int b = i % 100 / 10; // 获取十位数
int c = i % 10; // 获取个位数
if (i == a * a * a + b * b * b + c * c * c) {
System.out.println(i);
}
}
}
}
相关推荐
![](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)