java写100到999之间的水仙花数
水仙花数指一个n位数(n>=3),它的每个位上的数字的n次幂之和等于它本身。例如,153是一个水仙花数,因为1^3 + 5^3 + 3^3 = 153。
以下是Java代码,用于输出100到999之间的水仙花数:
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 ones = i % 10; // 获取个位数
int sum = (int) (Math.pow(hundreds, 3) + Math.pow(tens, 3) + Math.pow(ones, 3)); // 计算每个位上的数字的立方和
if (sum == i) { // 如果等于自身,则是水仙花数
System.out.println(i);
}
}
}
}
输出结果为:
153
370
371
407
原文地址: https://www.cveoy.top/t/topic/bqja 著作权归作者所有。请勿转载和采集!