java打印出所有的水仙花数所谓水仙花数是指一个三位数其各位数字立方和等于该数 本身。例如:153是一个水仙花数因为153=1的三次方+5的三次方+3的三次方。程序分析:利用for循环控制100-999个数每个数分解出个位十位百位。
以下是Java代码示例,用于打印出所有的水仙花数:
public class NarcissisticNumber {
public static void main(String[] args) {
for (int i = 100; i <= 999; i++) {
int hundreds = i / 100; // 获取百位数
int tens = (i / 10) % 10; // 获取十位数
int units = i % 10; // 获取个位数
int sum = (int) (Math.pow(hundreds, 3) + Math.pow(tens, 3) + Math.pow(units, 3));
if (sum == i) {
System.out.println(i);
}
}
}
}
运行以上代码,将会输出所有的水仙花数:
153
370
371
407
这些数满足条件:各位数字立方和等于该数本身。
原文地址: http://www.cveoy.top/t/topic/i4A3 著作权归作者所有。请勿转载和采集!