簡體   English   中英

取整數n並使用字符串格式將pi打印為n位的函數

[英]Function that takes integer n and prints pi to n digits using string formatting

我想通過將整數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

您的代碼缺少類型說明符:

from math import pi
import sys 

def print_pi(n):
    print(("%%.%df" % n) % pi) 

print_pi(int(sys.argv[1]))

使用新的(實際上是現在比較舊的) 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM