【问题标题】:Strange statement in if functionif函数中的奇怪语句
【发布时间】:2018-09-02 13:18:30
【问题描述】:

我从以下 python 函数得到了非常奇怪的输出:

s = "-8.8373347749999997e-08"
def roundNumb(numb, pos):
    print("roundNumb()", numb , pos)
    ret = ""
    if int(numb[pos]) < 5:
        ret = numb[:pos]
        print("if int(numb[pos]) < 5: ", int(numb[pos]), " ", ret)
    else:
        if int(numb[pos]) == 9:
            ret = roundNumb(numb , pos - 1)
            print("int(numb[pos]) == 9 ", int(numb[pos]), " ",ret)
        else:
            ret = numb[:(pos-1)] + str(int(numb[(pos-1)]) + 1)
            print("else:", ret)
    return ret


>>> roundNumb(s, 12)
roundNumb() -8.8373347749999997e-08 12
roundNumb() -8.8373347749999997e-08 11
if int(numb[pos]) < 5:  4   -8.83733477
int(numb[pos]) == 9  9   -8.83733477
'-8.83733477'

你可以看到 roundNumb 函数被调用了两次,但我真的不明白为什么。它应该在第一个 if 语句结束:

if int(numb[pos]) < 5:

【问题讨论】:

  • "-8.8373347749999997e-08"[12]'9'
  • 我不完全知道发生了什么,但它可能与符号 e 有关
  • 糟糕,原来是“e-08”。对不起
  • print 语句在函数递归之后执行。基本上print 输出是向后的。
  • 为什么不使用内置的四舍五入而不是依靠字符串表示来舍入你的数字?

标签: python python-3.x function


【解决方案1】:

你调用函数 roundNumb(s, 12) // where numb[pos] = 9

then 函数转到 else 块 并执行 if 块

if int(numb[pos]) == 9:

如果块执行你再次调用这个函数,这是在此之前感兴趣的部分

ret = roundNumb(numb , pos - 1) // and herer is function execution pause

print("int(numb[pos]) == 9 ", int(numb[pos]), " ",ret)

然后functoin在你的函数块中执行

if int(numb[pos]) < 5:

ret = numb[:pos]

print("if int(numb[pos]) < 5: ", int(numb[pos]), " ", ret)

然后执行这个打印函数然后那个暂停的函数恢复 然后执行这个打印函数

print("int(numb[pos]) == 9 ", int(numb[pos]), " ",ret)

有关递归的知识对理解这一点很有帮助

【讨论】:

  • @Aran-Fey 说明了正在发生的事情。谢谢。不再需要重播。
猜你喜欢
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 2020-09-09
相关资源
最近更新 更多