【问题标题】:Problems in for loop (python)for循环中的问题(python)
【发布时间】:2019-12-13 18:26:09
【问题描述】:

for 循环可以运行 33 次,但不能运行超过它。 我必须运行它 100 次。 谢谢你! for 循环必须运行 100 次,最后打印 "a" "profit" 和 "total"


a = 0
pluser = 0.01
total = 0
profit = 0
lasta = 0
lastProfit = 0
lastTotal = 0
counter = 0
for i in range (100):

        lasta = a
        lastTotal = total
        lastProfit = lasta * 14 - lastTotal
        a += pluser
        total += a
        profit = a * 14 - total
        while (profit <= lastProfit):

            pluser += 0.01
            a += pluser
            total += a
            profit = a * 14 - total
            counter += 1

print(a)
print(total)
print(profit)
print(counter)

【问题讨论】:

  • 它卡在了 while 循环中,因为 profit 在第 33 次迭代时总是递减。您正在从中减去 total
  • 请注意,total 在while 循环中可能大于14a,而且total 的增长速度可能快于a

标签: python loops for-loop compiler-errors qtquick2


【解决方案1】:

当我运行你的代码时,我得到了一个无限循环,因为你从利润中减去,所以它总是小于等于 0 的 lastProfit。

您可能想要检查您正在做什么以在循环中获利,以及您的起始变量。

我希望这会有所帮助!

:)

【讨论】:

    【解决方案2】:

    如果没有其他方法,您可以创建一个 while 循环和一个新变量。您可以设置 x = 1,然后每次运行时都会添加一个,因此它将在一百次后完成。确保 x + 1 是缩进的
    x = 1
    While x <= 100:
    x + 1

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多