java在控制台输出所有的“水仙花数”,并统计有多少个水仙花数。所谓的水仙花数是一个三位数,其各位 数字的立方和等于该数本身,例如153 = 1 **1 1 + 5 * 5 *5+ 3 * 3 *3
时间: 2023-05-21 09:05:35 浏览: 56
以下是 Java 代码,可实现控制台输出所有的水仙花数,并统计它们的个数:
```java
class Main {
public static void main(String[] args) {
int count = 0;
for(int i = 100; i <= 999; 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);
count++;
}
}
System.out.println("共有 " + count + " 个水仙花数。");
}
}
```
这段代码首先定义了一个变量 `count`,用于记录水仙花数出现的次数。接着,使用 for 循环遍历所有的三位数,将它们拆分成各个位上的数字,并判断它们是否符合水仙花数的定义。如果是水仙花数,则在控制台输出它,并将计数器 `count` 加一。最后,输出水仙花数的总数。
相关问题
用java在控制台输出所有的“水仙花数”,并统计有多少个水仙花数。所谓的水仙花数是一个三位数,其各位 数字的立方和等于该数本身
。代码如下:
```java
public class NarcissisticNumber {
public static void main(String[] args) {
int count = 0; // 计数器,记录水仙花数的个数
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);
count++;
}
}
System.out.println("共有" + count + "个水仙花数");
}
}
```
输出结果如下:
```
153
370
371
407
共有4个水仙花数
```
在控制台输出所有的“水仙花数”,并统计有多少个水仙花数。所谓的水仙花数是一个三位数,其各位 数字的立方和等于该数本身,例如153 = 1 **1 *1 + 5 * 5* *5+ 3 * 3 *3。
### 回答1:
count = 0
for num in range(100, 1000):
digit1 = num // 100
digit2 = (num // 10) % 10
digit3 = num % 10
if num == digit1 ** 3 + digit2 ** 3 + digit3 ** 3:
print(num)
count += 1
print("共有{}个水仙花数".format(count))
### 回答2:
水仙花数是一个三位数,其各位数字的立方和等于该数本身。为了解决这个问题,我们可以使用循环从100到999的所有三位数,并判断是否是水仙花数。
具体代码如下:
```python
count = 0 # 统计水仙花数的个数
for num in range(100, 1000):
# 获取百位、十位和个位上的数字
digit_hundreds = num // 100
digit_tens = (num // 10) % 10
digit_units = num % 10
# 判断是否是水仙花数
if num == digit_hundreds ** 3 + digit_tens ** 3 + digit_units ** 3:
count += 1
print(num, end = ' ')
print("总共有", count, "个水仙花数。")
```
运行上述代码后,控制台会输出所有的水仙花数,并统计有多少个水仙花数。
### 回答3:
水仙花数是一个三位数,其各位数字的立方和等于该数本身。
我们可以使用循环来遍历所有的三位数,然后计算每个数的各位数字的立方和,判断是否等于该数本身。如果等于,则打印该数,并将计数器加1。
```python
count = 0 # 计数器,用于统计水仙花数的个数
for num in range(100, 1000):
digit1 = num // 100 # 百位数字
digit2 = (num % 100) // 10 # 十位数字
digit3 = num % 10 # 个位数字
# 计算各位数字的立方和
sum_of_digit_cubes = digit1 ** 3 + digit2 ** 3 + digit3 ** 3
# 若立方和等于该数本身,则为水仙花数
if sum_of_digit_cubes == num:
print(num)
count += 1
print("一共有", count, "个水仙花数。")
```
运行上述代码,即可在控制台输出所有的水仙花数,并统计水仙花数的个数。