Skip to main content
 首页 » 编程设计

python之采用整数 n 并使用字符串格式将 pi 打印为 n 位数字的函数

2025年05月04日19xxx_UU

我想通过将整数 n 传递到字符串格式化字段来将 pi 打印到 n 小数位。但是,这给了我一个错误。执行此操作的正确方法是什么?

我的代码:

from math import pi 
def print_pi(n): 
    print(("%."+str(n)) % pi) 

错误:

Traceback (most recent call last): 
  File "1.2.3.py", line 4, in <module> 
    print_pi(5) 
  File "1.2.3.py", line 3, in print_pi 
    print(("%."+str(n)) % pi) 
ValueError: incomplete format 

请您参考如下方法:

使用新的(实际上,现在相当旧)format 方法更清晰:

>>> fmtstr = "{:.{}f}".format(math.pi, 2) 
>>> print(fmtstr) 
3.14 
>>> fmtstr = "{:.{}f}".format(math.pi, 10) 
>>> print(fmtstr) 
3.1415926536 

漂亮整洁:

>>> def print_pi(n, pi=math.pi): 
...     print("{:.{}f}".format(pi, n)) 
... 
>>> for i in range(10): 
...     print_pi(i) 
... 
3 
3.1 
3.14 
3.142 
3.1416 
3.14159 
3.141593 
3.1415927 
3.14159265 
3.141592654