我如何用百分比打印差异

问题描述 投票:0回答:2

我正在学校做文字游戏练习,我们必须为此做四个不同的功能。我已经完成了健康积分系统,现在我想打印出球员使用了总金额的百分比。

这是我的hp系统:

def hela(player_health, hit):
    return player_health - hit

player_health_points = 15
dog_hit_value = 4
pistol_hit_value = 15
brasnuckles_hit_value = 3
punch_hit_value = 1
kick_hit_value = 2
player_health_points = hela(player_health_points, dog_hit_value,)
player_health_points = hela(player_health_points, brasnuckles_hit_value)
print('You have ' + str(player_health_points) + ' HP left!')*

这就是我现在所做的,并因此失去了我的大脑:

def hp_left_percentage(x,y):
    vastaus = x - y
    return vastaus

health = 16
tulos = hp_left_percentage(health,player_health_points)
print(tulos)

问题:

  • 为什么我必须为def hp_left_percentage health添加一个,使其显示正确的值?

  • 现在def hp_left_percentage向我显示多少球员已经恢复健康了,并带有数值。我如何获得功能打印它的百分比?

我希望你能理解我的意思:)

python function percentage
2个回答
0
投票

您的意思是这样的吗?

def hp_left_percentage(x,y):
    vastaus = x - y
    percentage = '{0:.2f}'.format((vastaus / x * 100))
    return vastaus

0
投票

如果我正确理解了您的问题,您想显示剩余的健康百分比,而不仅仅是绝对数字?现在,您的health_left_percentage仅显示HP中的数字差异。要计算百分比,可以将其更改为:

def hp_left_percentage(x,y):
    # I assume, 'y' is the damage here.

    vastaus = (x - y) / x
    print(f'You have {vastaus:.0%} HP left!')

这样,函数将自动计算百分比并以正确格式返回它。我建议阅读f字符串,以一种干净的方式显示带有所需变量的字符串。

希望这会有所帮助。让我知道我是否误解了您。

编辑如果玩家被击中两次或两次以上,则应将初始HP存储在全局变量中,并按如下所示更改功能:

initial_hp = 100


def hp_left_percentage(x, y):
    vastaus = (x - y) / initial_hp
    return vastaus


perc_left = hp_left_percentage(x, y)
print(f'You have {perc_left:.0%} HP left!')
© www.soinside.com 2019 - 2024. All rights reserved.