输出水仙花数以及个数用JAVA
时间: 2023-03-30 16:03:26 浏览: 63
好的,我可以回答这个问题。水仙花数是指一个三位数,其各位数字的立方和等于该数本身。例如,153是一个水仙花数,因为1^3 + 5^3 + 3^3 = 153。以下是用JAVA输出水仙花数及其个数的代码:
public class NarcissisticNumber {
public static void main(String[] args) {
int count = ;
for (int i = 100; i < 100; 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);
count++;
}
}
System.out.println("水仙花数的个数为:" + count);
}
}
相关问题
java输出所有水仙花数以及水仙花数的个数
水仙花数是指一个n位数,它的每个位上的数字的n次幂之和等于它本身。在Java中,可以通过以下代码输出所有的水仙花数,并计算水仙花数的个数:
```java
public class NarcissisticNumber {
public static void main(String[] args) {
int count = 0; // 计数器,用于统计水仙花数的个数
for (int i = 100; i < 1000; i++) {
int num = i;
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += Math.pow(digit, 3);
num /= 10;
}
if (sum == i) {
System.out.println(i);
count++;
}
}
System.out.println("水仙花数的个数为:" + count);
}
}
```
运行以上代码,即可输出所有的水仙花数,并统计水仙花数的个数。
使用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);//输出水仙花数
}
}
}
}
```