java24、打印出所有的水仙花数所谓水仙花数是指一个三位数其各位数字立方和等于该数 本身。例如:153是一个水仙花数因为153=1的三次方+5的三次方+3的三次方。
以下是打印出所有的水仙花数的Java代码:
public class NarcissisticNumber {
public static void main(String[] args) {
for (int i = 100; i < 1000; 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/i4AV 著作权归作者所有。请勿转载和采集!