简体   繁体   English

如何在 Python 中舍入浮点数?

[英]How to round float numbers in Python?

I know there are different questions like this;我知道有这样的不同问题; and I searched my question on stackoverflow and many other webs, and basically the easiest way to do this is using the round/2 function, but the round function didn't work properly... Here's part of my code using the round function: and I searched my question on stackoverflow and many other webs, and basically the easiest way to do this is using the round/2 function, but the round function didn't work properly... Here's part of my code using the round function:

ad=150
ad_percent = 75
ap=150
ap_percent=55
armor_pen=35
enemy_armor=125
enemy_max_hp=1000

ap = ap_percent * ap / 100
ad = ad_percent * ad / 100

armor_less = armor_pen * enemy_armor / 100
enemy_armor = enemy_armor - armor_less
# Till now, all is good.

round(ad)
print(ad)

Output Output

112.5 112.5

So... It's not working.所以......它不起作用。 How can I make that variable round to 113?如何使该变量舍入到 113?

Thanks for helping.感谢您的帮助。

round() returns the rounded value ; round()返回四舍五入的值 it doesn't modify its argument (indeed, it couldn't, in Python's data model (unless __round__ on a custom object had been modified to mutate the object itself, but that would be very, very icky, and I digress)). it doesn't modify its argument (indeed, it couldn't, in Python's data model (unless __round__ on a custom object had been modified to mutate the object itself, but that would be very, very icky, and I digress)).

You'll need to assign the return value of round() , in other words eg您需要分配round()的返回值,换句话说,例如

ad = round(ad)

instead.反而。

You are properly rounding but you are not storming it in a variable to print afterwards.您正在正确舍入,但您并没有在变量中猛冲它以便之后打印。

You can try:你可以试试:

print(round(ad))

Or:或者:

ad_rounded = round(ad)
print(ad_rounded)

Hope it helps.希望能帮助到你。 Let me know if it did.让我知道是否有。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM