python - 不理解输出中带小数的字符串格式()方法
问题描述
我正在通过 python 终端中的基本数学运算并使用格式来管理输出。
我尝试生成小数点后 10 位的输出。
print('{0:.10f}'.format(1.0/3))
得到这个输出 0.3333333333
我再次尝试生成小数点后 20 位的输出
print('{0:.20f}'.format(1.0/3))
得到这个输出为 0.33333333333333331483
我认为这应该返回 0.3333333333333333333
为什么格式功能无法按预期工作。
解决方案
格式化功能正常工作。这主要是因为编程语言在从除法产生小数时对浮点精度的限制。
我鼓励你在这里阅读。 https://docs.python.org/3/tutorial/floatingpoint.html