使用Java写出水仙花数
水仙花数是指一个三位数,其各位数字的立方和等于该数本身。例如,153是一个水仙花数,因为1³+5³+3³=153。
下面是使用Java编写的水仙花数代码:
public class NarcissisticNumber {
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
int hundredsDigit = i / 100; // 百位数
int tensDigit = (i / 10) % 10; // 十位数
int unitsDigit = i % 10; // 个位数
int sum = hundredsDigit * hundredsDigit * hundredsDigit + tensDigit * tensDigit * tensDigit + unitsDigit * unitsDigit * unitsDigit;
if (sum == i) {
System.out.println(i + " 是一个水仙花数");
}
}
}
}
该程序首先从100开始循环到999,对于每个三位数,分别计算它的百位数、十位数和个位数。然后按照水仙花数的定义,计算出它们的立方和,并判断是否等于该数本身。如果等于,则输出该数是一个水仙花数
原文地址: https://www.cveoy.top/t/topic/hq3G 著作权归作者所有。请勿转载和采集!