Java实现打印出 100~1000 范围内的所有“水仙花数” 所谓“水仙花数”是指一个三位数 其各位上的数字立方和等于该数本身。 例如:153 是一个“水仙花数”, 因为 153=1^3 +5 ^3+3^3
时间: 2023-10-27 19:19:07 浏览: 37
好的,以下是 Java 代码实现:
```java
public class Main {
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);
}
}
}
}
```
输出结果为:
```
153
370
371
407
```
这些数字都是 100~1000 范围内的水仙花数。
相关问题
用java语言编写打印出100~1000范围内的所有水仙花数
水仙花数是指一个三位数,其各位数字的立方和等于该数本身。例如,153是一个水仙花数,因为 $1^3 + 5^3 + 3^3 = 153$。以下是用Java编写的程序打印出100~1000范围内的所有水仙花数:
```
public class NarcissisticNumber {
public static void main(String[] args) {
for (int i = 100; i <= 1000; i++) {
int hundredsDigit = i / 100;
int tensDigit = (i / 10) % 10;
int unitsDigit = i % 10;
if (hundredsDigit * hundredsDigit * hundredsDigit + tensDigit * tensDigit * tensDigit + unitsDigit * unitsDigit * unitsDigit == i) {
System.out.println(i);
}
}
}
}
```
在这个程序中,我们使用了一个 for 循环来遍历 100~1000 范围内的所有三位数。然后,我们将每个三位数拆分成它的百位数、十位数和个位数,并将其保存在变量 hundredsDigit、tensDigit 和 unitsDigit 中。接下来,我们使用一个 if 语句来检查当前的三位数是否为水仙花数,如果是就打印出来。
用java打印出100~1000范围内的所有 “水仙花数”,所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数本身
以下是Java代码实现:
```java
public class NarcissisticNumber {
public static void main(String[] args) {
for (int i = 100; i <= 999; 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);
}
}
}
}
```
输出结果为:
```
153
370
371
407
```