【问题标题】:multiplication of numbers from while loop来自while循环的数字相乘
【发布时间】:2023-04-07 14:40:02
【问题描述】:

我正在尝试将我从 while 循环中获得的数字相乘。 像 1.1 * 1.2 * 1.3 ... * 2 - 数字从 1.1 开始,停在 2 我已经这样做了,但它给了我 4.41 而不是 67.04,有什么问题?我需要使用 for 循环来编写它吗? 脚本:

count = 1.1

while count < 2.1:
    print(count)
    count += 0.1

print(round(count * count, 3))

【问题讨论】:

  • 好吧,count == 2.1,所以count * count == 4.41。有什么问题?请注意,您不会在循环本身中乘以任何内容。
  • 我想实现这个:1.1 * 1.2 * 1.3 ... * 2
  • 如果我尝试 count *= 0.1 会导致无限循环
  • 当然:1.1 * 0.1 * 0.1 * 0.1 == 0.0011。如果你继续乘以小于 1 的值,你最终会将数字缩小到零

标签: python python-3.x loops while-loop


【解决方案1】:
out = 1
for i in range(11,21):
    out *= i/10

print(out)

输出:

67.04425728

【讨论】:

    【解决方案2】:

    我添加了一个 final_product 变量,它将乘以每个更新的计数值,也许这会有所帮助:

    count = 1.1
    final_product = 1
    while count < 2.1:
        print(count)
        final_product*=count
        count += 0.1
    print(round(final_product, 2))
    

    你做的一切都很完美,但你需要添加一些东西来捕获新的更新值(0.1)并乘以自身以获得最终产品,即 67.04。

    【讨论】:

    • 非常感谢,现在我明白为什么它不起作用了
    猜你喜欢
    • 2014-02-17
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 2022-12-07
    • 2014-10-16
    相关资源
    最近更新 更多