水仙花数是指一个三位数,其每个位上数字的立方和等于该数本身。例如,153是一个水仙花数,因为 $1^3 + 5^3 + 3^3 = 153$。下面是Python实现水仙花数的代码:

for i in range(100, 1000):
    # 获取百位、十位和个位数字
    hundreds = i // 100
    tens = (i // 10) % 10
    ones = i % 10
    # 判断是否为水仙花数
    if i == hundreds ** 3 + tens ** 3 + ones ** 3:
        print(i)

代码中使用了一个for循环,遍历从100到999之间的所有整数。在每次循环中,首先获取这个整数的百位、十位和个位数字,然后判断是否为水仙花数。如果是,就打印出来。

用Python实现水仙花数

原文地址: https://www.cveoy.top/t/topic/byxA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录