java打印水仙花数
时间: 2023-11-16 13:54:51 浏览: 134
好的,以下是 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 / 10 % 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) {
for (int i = 100; i < 1000; i++) {
int a = i / 100;
int b = i / 10 % 10;
int c = i % 10;
if (i == a * a * a + b * b * b + c * c * c) {
System.out.println(i);
}
}
}
}
```
该程序会打印出所有三位数的水仙花数。
用Java打印水仙花数
Sure! 下面是Java代码实现水仙花数的功能:
```
public class NarcissisticNumber {
public static void main(String[] args) {
for (int i = 100; i <= 999; i++) {
if (isNarcissisticNumber(i)) {
System.out.print(i + " ");
}
}
}
public static boolean isNarcissisticNumber(int num) {
int sum = 0;
int temp = num;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
return sum == num;
}
}
```
这个代码会打印出100~999之间所有的水仙花数(即每个数字的立方和等于该数字本身),包括153、370、371、407。
阅读全文
相关推荐











