我如何打印百分比差异

How i can print difference with percentage

我正在为学校做文字游戏练习,我们必须为它制作四个不同的功能。我已经完成了生命值系统,现在我想打印玩家使用了多少百分比的总金额。

这是我的惠普系统:

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)

问题:

希望你能明白我的意思:)

如果我对你的问题理解正确,你想显示剩余生命值的百分比,而不仅仅是绝对值?现在你的 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!')

这样函数将自动计算百分比并return以正确的格式显示。我建议阅读 f-strings 以获得一种干净的方式来按照您希望的方式显示带有变量的字符串。

希望这对您有所帮助。如果我误解了你,请告诉我。

编辑 如果玩家被击中两次或更多次,那么你应该将初始 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!')

你的意思是这样的吗?

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

我正在休假,所以没有写在这里。感谢所有答案。

这就是我所做的。

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

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

player_health_points = 15

dog_hit_value = 4

player_health = 15
initial_hp = 15

player_health_points = hela(player_health_points, dog_hit_value,)

perc_left = hp_left_percentage(player_health, player_health_points)

print(f'You have {perc_left:.2%} HP left!')