简体   繁体   English

如何将浮点数转换为 integer 以便在 randint 中使用

[英]How do you convert a float to an integer so that it can be used in randint

I'm making a game and I have a feature that when the player levels up, their health increases.我正在制作一个游戏,我有一个功能,当玩家升级时,他们的健康会增加。 There is also a function that when the player rests, it heals the player for a random amount between 1 and a quarter of their max health.还有一个 function ,当玩家休息时,它会在玩家最大生命值的 1 到四分之一之间随机治疗。 The max health at level 2 is 30 so when quartered, goes to 7.5 and this doesn't work in a randint(1, p_maxhealth) and gives me this error; 2 级的最大生命值是 30,所以当四等分时,变为 7.5,这在 randint(1, p_maxhealth) 中不起作用并给我这个错误;

ValueError: non-integer stop for randrange(). ValueError:randrange() 的非整数停止。

I've tried converting the float to an int after quartering it but doing;我尝试在将浮点数四等分之后将其转换为 int ; int(round(p_maxhealth)) but it doesn't update the value to the int data type. int(round(p_maxhealth)) 但它不会将值更新为 int 数据类型。 Does anyone know how to work around this without manually setting the health to a new value as I would prefer not to:)有谁知道如何在不手动将运行状况设置为新值的情况下解决此问题,因为我不希望这样做:)

here is my code:这是我的代码:

p_hp = 25
p_maxhp = 30

rested_maxhp = p_maxhp / 4
int(round(rested_maxhp))  
print(rested_maxhp)
rested_hp = randint(1,rested_maxhp) 
print(rested_hp)
p_hp = min(p_hp + rested_hp, p_maxhp)   
print(p_hp)

Running the int() function doesn't change the variable itself, so this would work:运行int() function 不会改变变量本身,所以这会起作用:

from random import randint
p_hp = 25
p_maxhp = 30

rested_maxhp = p_maxhp / 4

rested_maxhp = int(round(rested_maxhp)) //This changed

print(rested_maxhp)

rested_hp = randint(1, rested_maxhp)

print(rested_hp)

p_hp = min(p_hp + rested_hp, p_maxhp)

print(p_hp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python中将list / pyodbc.row转换为字符串,以便可以使用str.replace? - How do you convert a list/pyodbc.row to a string in python so that str.replace can be used? 如果将整数值更改为浮点数,如果是整数要浮点数如何更改? - If a integer value is changed to a float, how do you change if it is an integer to float? 如何连接整数和字母,以便结果保持整数 - How do you concatenate an integer and letter so that the result remains an integer 如何在Python中将字符串转换为整数 - How do you convert a string to an integer in Python 如何将 tkinter 条目转换为整数 - How do you convert a tkinter entry to an integer 如何将非整数字符串转换为浮点数? - How do I convert a non-integer string into a float? 如何将浮点矩阵转换为 integer 矩阵? - How do I convert a float matrix into integer matrix? 如何将set转换为float或integer - How to convert set to float or integer 如何实现串行设备使用的自定义代码页,以便我可以在 Python 中将文本转换为它? - how do I implement a custom code page used by a serial device so I can convert text to it in Python? 如何修复 Python 中的“无法将字符串转换为浮点数”? - How do you fix “could not convert string to float” in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM