如何生成随机浮点数然后将浮点数舍入到Python 3.4中的最接近小数点?
答案 0 :(得分:1)
假设你想要一个介于0.0和1.0之间的浮点数,你可以用:
f5::
run, C:\test.txt, , , o_pid
WinWait, ahk_pid %o_pid%
WinMove, ahk_pid %o_pid%, ,500, 250, 200, 100
return
(注意除法是10.0而不是10来强制浮动操作)
输出:
0.2
0.6
0.8
...
答案 1 :(得分:1)
方法1:
您需要两件事:The random module和内置函数round()
。
首先你需要一个随机数。这很简单:
import random
a = random.random()
这将产生一个介于0和1之间的数字。接下来使用round()
对其进行舍入:
b = round(a, 1) # Thanks to https://stackoverflow.com/users/364696/shadowranger for the suggestion
print(b)
round()
中的第二个参数指定了它在这种情况下舍入到的小数位数1,这意味着它将舍入到1个小数位。
并完成了。
方法2:
另一种方法是使用random.randint()
这将产生一个范围内的整数,然后我们可以除以10得到一个小数位:
import random # get the random module
a = random.randint(1, 9) # Use the randint() function as described in the link above
b = a / 10 # Divide by 10 so it is to 1 decimal place.
print(b)
和你的完成