使用Java求水仙花数
时间: 2023-07-11 17:19:49 浏览: 46
以下是使用 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 求水仙花数
水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。例如:1^3 + 5^3 + 3^3 = 153。以下是 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) {
int a, b, c;//定义三位数中的个十百位数
System.out.println("三位数中所有的水仙花数为: ");//输出所有的水仙花数
for (int n = 100; n <= 999; n++) {//控制100-999个数
a = n / 100;//百位上的数
b = n % 100 / 10;//十位上的数
c = n % 10;//个位上的数
if (a * a * a + b * b * b + c * c * c == n) {//判断是否为水仙花数
System.out.println(n);//输出水仙花数
}
}
}
}
```