用Python编程打印出水仙花数
水仙花数是指一个三位数,它的各位数字的立方和等于该数本身。例如,153是一个水仙花数,因为1³+5³+3³=153。以下是用Python编程打印出所有水仙花数的代码:
for num in range(100, 1000):
# 将百位、十位、个位分离出来
hundreds = num // 100
tens = (num // 10) % 10
ones = num % 10
# 判断是否为水仙花数
if num == hundreds**3 + tens**3 + ones**3:
print(num)
输出结果为:
153
370
371
407
原文地址: https://www.cveoy.top/t/topic/NdB 著作权归作者所有。请勿转载和采集!