checkily 发表于 2018-2-10 23:26:30

从水仙花数发现的问题,想不明白,求解释

本帖最后由 checkily 于 2018-2-10 23:28 编辑

程序1,result=0放在for循环里面,能算出正确的结果:
def fun1():
   
    for each in range(100,1000):
      result=0
      temp1=each
      while temp1:
            temp=temp1%10
            result=result+temp**3
            temp1=temp1//10

      if result==each:
            print(each)
fun1()

程序2,result=0放在for 循环上面,算不出结果,为什么呢?不是都是初始化result吗?
def fun1():
    result=0
   
    for each in range(100,1000):      
      temp1=each
      while temp1:
            temp=temp1%10
            result=result+temp**3
            temp1=temp1//10

      if result==each:
            print(each)
fun1()

lies_for_L 发表于 2018-2-11 00:22:15

放在外面每次循环不置零,
每个数的结果都会累加

checkily 发表于 2018-2-11 00:28:34

lies_for_L 发表于 2018-2-11 00:22
放在外面每次循环不置零,
每个数的结果都会累加

哦,原来如此,我明白了。
页: [1]
查看完整版本: 从水仙花数发现的问题,想不明白,求解释