Gou*_*war 0 python printing random decimal range
如何选择一个生成的十进制值并将其转换为变量.
for i in range(10):
print (random.random() * (0.909 - 0.101) + 0.101)
Run Code Online (Sandbox Code Playgroud)
另外我如何使该变量只有三个小数位,它必须在变量而不是打印我应该能够简单地这样做而不是在打印中生成小数我想在变量中做它并选择一个值?
print = (myVar)
Run Code Online (Sandbox Code Playgroud)
您希望使用您的打印功能执行以下操作:
print("{0:.3f}".format(result))
Run Code Online (Sandbox Code Playgroud)
如评论中所述,如果选择使用该方法,则支持旧式字符串格式的替代方法.解决方案也可以通过以下方式实现:
print("%0.3f" % result)
Run Code Online (Sandbox Code Playgroud)
使用该格式化程序只会将结果打印为三位小数.
演示:
from random import random
for n in range(10):
result = random() * (0.909 - 0.101) + 0.101
print("{0:.3f}".format(result))
Run Code Online (Sandbox Code Playgroud)
输出:
0.323
0.721
0.665
0.831
0.141
0.297
0.643
0.456
0.716
0.320
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101 次 |
| 最近记录: |