首页 > 解决方案 > 如何将变量减少为零?

问题描述

我有一个由任何用户输入到我的程序的变量。我无法开始工作的任务是我希望变量在可变时间的过程中从输入值减小到 0(也由用户输入)。在伪代码中类似于:

x = time_variable
y = decreasing_variable
z = amount_of_decrease_of_y
while i < x:
    y = y - z;

我已经尝试编写代码,但它不能正常工作:

time_of_activity = float(input('How long should health decrease in hours? '))
time_of_activity = time_of_activity * 60 * 60
health = float(input('How much is starting health? '))
X = health / time_of_activity 

def healthdecrease():
   i = 1
   while i<(time_of_activity):
    time.sleep(1)
    i+=1
    health = health - X

decrease_of_health = threading.Thread(target=healthdecrease)
decrease_of_health.start()

这是我到目前为止的代码。它似乎遗漏了一些东西,但我无法弄清楚。

标签: pythonthread-sleepdecrement

解决方案


在大多数情况下,代码的逻辑是正确的,但是没有迹象表明 pythonhealth是一个全局变量。这必须在health_decrease方法中明确完成,以便它使用现有的全局变量,而不是创建一个新的局部变量。
除此之外,某些格式(更具体地说,缩进)已关闭。
最后,我max()在减去时添加了一个组件decrementhealth以确保由于浮点舍入错误,该值永远不会低于 0。

这是一个功能代码示例(没有线程):

import time

time_of_activity = float(input('How long should health decrease for in seconds? '))

health = float(input('What is the starting health? '))
decrement = health / time_of_activity 

def health_decrease():
    global health
    i = 1
    while i <= time_of_activity:
        time.sleep(1)
        i += 1
        health = max(health - decrement, 0)

health_decrease()

推荐阅读