【问题标题】:Assign values to next digits为下一个数字赋值
【发布时间】:2023-03-05 21:42:01
【问题描述】:

我需要为下一个数字分配一个值。代码如下:

def numerujPoziomy():
    for i in range(0, liczbaPoziomow, 1):
        var = i + 1
        rootValue = 1
        y = rootValue
        print 'Level', var, 'value', y

每个下一个级别都必须比上一个级别小一半。 Root 的值为 1,下一级的值为 0.5,下一级的值为 o.25,等等。我不知道该怎么做。

我的代码结果:

Level 1 value 1
Level 2 value 1
Level 3 value 1
Level 4 value 1
Level 5 value 1
Level 6 value 1

但我需要这个结果:

Level 1 value 1
Level 2 value 0.5
Level 3 value 0.25
Level 4 value 0.125
Level 5 value 0.0625
Level 6 value 0.03125

【问题讨论】:

  • 那里不应该有/ 2.0吗?你到底有什么问题?
  • 欢迎来到 SO Seweryn!请记住,这里的问题应该显示重要的研究(答案不应该是现成的)并适用于其他人(尽可能使问题笼统)。
  • 预期的结果是有用的,所以我回滚了你的编辑

标签: python list python-2.7 loops for-loop


【解决方案1】:

你可以提高 1/2 的第 i 次方。

liczbaPoziomow = 5

def numerujPoziomy():
    for i in range(0, liczbaPoziomow):
        print 'Level', i + 1, 'value',  0.5 ** i

numerujPoziomy()
>>> Level 1 value 1.0
>>> Level 2 value 0.5
>>> Level 3 value 0.25
>>> Level 4 value 0.125
>>> Level 5 value 0.0625

【讨论】:

  • 你的方法更快
  • 非常感谢您的快速回答。现在生活更轻松了:)
【解决方案2】:

你使用了2**i的倒数:

def numerujPoziomy():
    for i in range(0, liczbaPoziomow, 1):
        print 'Level', i+1, 'value', 1./2**i

请注意,在 python 2.x 中,1./2**i 而不是1/2**i非常重要的,因为后者只会返回一个整数,而不是你想要的浮点数。在 Python 3 中或通过在文件开头使用 from __future__ import division 可以避免此问题。

【讨论】:

  • "你用的是2**i的倒数"当然是0.5 ** i
【解决方案3】:

一个简单的方法是:

def numerujPoziomy():
    rootValue = 1.0
    for i in range(0, liczbaPoziomow, 1):
        var = i + 1
        y = rootValue / 2
        rootValue = y
        print 'Level', var, 'value', y

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2018-07-13
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多