4. (循环结构)利用任意2种循环结构,实现“水仙花数”的查找和输出,完整写出3种循环,Java代码
时间: 2024-10-19 22:06:42 浏览: 31
"水仙花数"是指一个三位数,其各位数字立方之和等于该数本身。例如,153是一个水仙花数,因为1^3 + 5^3 + 3^3 = 153。
以下是三种常见的循环结构(for、while和do-while)在Java中寻找并输出水仙花数的示例:
**1. for循环:**
```java
for (int num = 100; num <= 999; num++) {
int firstDigit = num / 100;
int secondDigit = (num % 100) / 10;
int thirdDigit = num % 10;
if (Math.pow(firstDigit, 3) + Math.pow(secondDigit, 3) + Math.pow(thirdDigit, 3) == num) {
System.out.println(num);
}
}
```
**2. while循环:**
```java
int num = 100;
while (num <= 999) {
int firstDigit = num / 100;
int secondDigit = (num % 100) / 10;
int thirdDigit = num % 10;
if (Math.pow(firstDigit, 3) + Math.pow(secondDigit, 3) + Math.pow(thirdDigit, 3) == num) {
System.out.println(num);
}
num++;
}
```
**3. do-while循环:**
```java
int num = 100;
do {
int firstDigit = num / 100;
int secondDigit = (num % 100) / 10;
int thirdDigit = num % 10;
if (Math.pow(firstDigit, 3) + Math.pow(secondDigit, 3) + Math.pow(thirdDigit, 3) == num) {
System.out.println(num);
}
} while (num++ < 1000);
```
阅读全文