开发者

How can I write this without so many floats?

开发者 https://www.devze.com 2023-02-01 07:06 出处:网络
float(float(1)/flo开发者_运维百科at(i) * float(score)) Assuming Python 2.x: 1.0 / i * score The main case you need to worry about is the division because in Python 2.x, division is defaulted to integ
float(float(1)/flo开发者_运维百科at(i) * float(score))


Assuming Python 2.x: 1.0 / i * score

The main case you need to worry about is the division because in Python 2.x, division is defaulted to integer division. In order to have floating-point division, either the dividend or divisor needs to be a float, hence the 1.0. Thus, 1.0/i will be a float, and multiplying a float by score (which can either be an integer or float) will result in another floating-point number.

In python 3.x, however, division defaults to floating-point division, so 1 / i * score would work.


What you want is simply float(score)/i in Python2. If one operand is a float, then the result will be a float too ,so code like score/float(i) or 1.0*score/i works as well.

You can also put from __future__ import division at the top of your .py file and you have float division by default. This means you can write score/i and it will be a float, like in Python3.


1.0 * score / i; should do it


Unless I'm totally wrong, a simple 1.0 / i * score should result in a float. I'm not sure if that's Python 3 only.

0

精彩评论

暂无评论...
验证码 换一张
取 消