数学。地板不能使数字四舍五入

2024-09-29 23:26:38 发布

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

我试着编写一个代码来测试一些东西,比如floor和ceil功能,但出现了一些问题,下面是代码:

import random
import math

difficolty = 3
healt = 50
potion_healt = random.randint(20,50)/3

healt = healt + potion_healt

if difficolty < 3:
   math.ceil(healt)

else:
   math.floor(healt)

print(f"You have {healt} ps!")

即使我使用了math.floor函数,输出结果如下:

You have 63.666666666666664 ps!

Process finished with exit code 0

如果我将难度设置为1或2,代码输出就不是这样了


Tags: 代码import功能youifhaverandommath
2条回答

您需要将math.floor/math.ceil的输出重新分配给变量health

固定版本:

import random
import math

difficolty = 3
healt = 50
potion_healt = random.randint(20,50)/3

healt = healt + potion_healt

if difficolty < 3:
   # reassign value to healt
   healt = math.ceil(healt)

else:
   # reassign value to healt
   healt = math.floor(healt)

print(f"You have {healt} ps!")

除此之外:你应该学习一点英语,因为变量名的正确发音是与其他贡献者保持大型代码库的基础

math.ceilmath.floor都不会更改其参数。相反,您需要将返回值分配给一个变量(与您传入的相同,或者另一个,取决于您尝试执行的操作)

相关问题 更多 >

    热门问题