当前位置: 代码迷 >> python >> 计算使用循环的次数
  详细解决方案

计算使用循环的次数

热度:33   发布时间:2023-06-16 10:20:26.0

因此,我建立了一个简单的while循环来检查需要多少击打来冷却茶。 一击可将茶温度降低10C。 问题是我不知道该如何进行。 我知道它很简单,但是刚开始使用python。 谢谢

tea = 100 #temperature of tea to start with
while tea >= 70:
    print (str(tea) + " C")
    tea = tea - 10
print (" It's ready now ... ")
tea = 100 #temperature of tea to start with
count = 0
while tea >= 70:
   print (str(tea) + " C")
   tea = tea - 10
   count += 1
print (" It's ready now ... ")

一种实现方法是在循环外添加一个变量,并在每次迭代中将其递增。 所以:

tea = 100
count = 0
while tea >= 70:
    print(str(tea) + " C")
    tea -= 10   # shorthand for tea = tea-10
    count += 1
print("It's ready now")
print("It took {} blows to cool down".format(count))

为什么需要循环?

def steps(current, target, step):
    return int(math.floor((current - target) / float(step)) + 1)

print("It took {} steps!".format(steps(100, 70, 10)))
  相关解决方案