python - 在 print() 方法中格式化小数位?

标签 python python-3.x

我正在尝试编写一个程序来求莱布尼茨级数的第 n 项之和。

我想在不同的行上打印答案,精确到小数点后 15 位。

代码。

a=[]
for _ in range(int(input().strip())):
   n=int(input().strip())
   a.append(sum([(-1)**i/(2*i+1) for i in range(n)]))
print("\n".join(str(i) for i in a))

我的输出:

0.7604599047323508
0.77290595166696

预期输出:

0.760459904732351
0.772905951666960

注意-我想使代码尽可能少

最佳答案

如果你愿意,

0.7604599047323508

像这样四舍五入到小数点后 15 位,

0.760459904732351

这非常简单:

i = 0.7604599047323508
print(i)
print("%.15f" % i) 

输出:

0.7604599047323508
0.760459904732351

如果您的十进制长度小于15。则添加0。看一下,

x = 0.760459904732 #Less than 15

print(x)
print("%.15f" % x)

输出:

0.760459904732
0.760459904732000

更新:

还有一个内置函数round(),您也可以使用它。 轮(值,地点)

示例:

>>> a=0.7604599047323508
>>> round(a,15)
0.760459904732351

对于您的代码:使用print()

a=[]
for __ in range(int(input().strip())):
   n=int(input().strip())
   a.append(sum([(-1)**i/(2*i+1) for i in range(n)]))

for i in a:
    print("%.15f" % i)

另外你为什么使用_?请改用其他名称。要了解 _ 的用途,请在解释器中尝试此操作。

>>> a=10
>>> b=20
>>> a+b
30
>>> _
30
>>> a*10000
100000 variable name.
>>> _
100000
>>> a
10

_ 存储解释器中最新的计算结果。 _ 用作一次性变量 __ 我猜比 _ 更好。

关于python - 在 print() 方法中格式化小数位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44858836/

相关文章:

带有 Emacs 的 Python 3

python - 使用 SQLAlchemy 获取页面的特定数量的结果

python - 如何处理 Pandas 中的多值线终止符

python - 有没有理由不发送 super().__init__() 字典而不是 **kwds?

python - python setuptools 的所有安装后选项都损坏了吗?

python - 如何从 Spotify 获取 Oauth token

python - 如何将二级索引更改为 pandas DataFrame 中的二级列?

python - 在新终端中运行辅助脚本

python - ZODB python : how to avoid creating a database with only one big entry?

python - 使用 Python 的 fixture 模块生成 fixture 数据