|
发表于 2022-10-5 23:39:25
|
显示全部楼层
本帖最后由 jackz007 于 2022-10-5 23:45 编辑
为了便于研究,先改写一下代码
- def Narcissus(k):
- r = False
- temp = k
- sum = 0
- while temp:
- sum = sum + (temp % 10) ** 3
- temp = temp // 10
- if sum == k:
- r = True
- return r
- for i in range(100 , 1000):
- if Narcissus(i):
- print(i)
复制代码
此代码的运行结果与楼主的代码完全相同,不同之处只是在于把水仙花数的枚举循环安排在了主程序,而楼主的代码是安排在了函数内。
下面,对代码稍作改动,其中,对 Narcissus() 函数的修改纯粹是为了显示中间过程,对水仙花数求取的运算本身没有施加任何影响。
这是代码
- def Narcissus(k):
- r = False
- temp = k
- sum = 0
- c = 0
- while temp:
- print('第%d次循环:temp = %3d , temp %% 10 = %d , temp // 10 = %3d' % ((c + 1) , temp , (temp % 10) , (temp // 10)) , end = '')
- sum = sum + (temp % 10) ** 3
- print(' , sum = %3d' % sum)
- temp = temp // 10
- c += 1
- if sum == k:
- r = True
- return r
- i = 371
- if Narcissus(i):
- print(i)
复制代码
请仔细观察代码的运行结果:
- D:\[00.Exerciese.2022]\Python>python x.py
- 第1次循环:temp = 371 , temp % 10 = 1 , temp // 10 = 37 , sum = 1
- 第2次循环:temp = 37 , temp % 10 = 7 , temp // 10 = 3 , sum = 344
- 第3次循环:temp = 3 , temp % 10 = 3 , temp // 10 = 0 , sum = 371
- 371
- D:\[00.Exerciese.2022]\Python>
复制代码
怎么样,这个计算过程应该很清晰了吧? |
|