如何将变量减为零?

2024-09-27 00:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由任何用户输入到我的程序的变量。 我无法完成的任务是,我希望变量在一段可变时间内(也由用户输入)从输入值减少到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()

这就是我目前掌握的代码。它似乎遗漏了什么,但我想不出来


Tags: of代码用户程序inputtime时间activity
2条回答

您没有正确调用healthdecrease函数。应该是这样的:

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

I guess you can just do it like this:

def healthdecrease():
 while(health):
   health -= x

在大多数情况下,代码的逻辑是正确的,但是python没有指出health是一个全局变量。这必须在health_decrease方法中显式完成,以便它使用现有的全局变量,而不是创建新的局部变量。
除此之外,某些格式(更具体地说,缩进)已关闭。
最后,我在从health中减去decrement时添加了一个max()组件,以确保该值不会由于浮点舍入错误而低于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()

相关问题 更多 >

    热门问题