这是我目前的代码:
x = int(3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679)
q = int(input("How many digits of Pi would you like to Print?"))
print(x[1:y])
对不起,如果代码缩进的内容不起作用,我不明白。
你知道,我知道它不能将字符串变量作为文字术语转换为整数,但我会从这里做些什么呢?
代码应该将Pi打印到选定数量的字符。
答案 0 :(得分:1)
您可以使用string formatting执行此任务。要获得可变数量的小数,您只需要参数化该值
from decimal import Decimal
x = decimal(3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679)
q = int(input("How many digits of Pi would you like to Print?"))
print("{0:.{width}f}".format(x, width=q))
请注意,print语句中的width
变量是您的用户输入。另请注意,我将pi
的定义从int
更改为decimal
(因为float
失去了精确度。)
示例:
How many digits of Pi would you like to Print?5
3.14159
How many digits of Pi would you like to Print?10
3.1415926536
How many digits of Pi would you like to Print?25
3.1415926535897931159979635
答案 1 :(得分:1)
请尝试以下代码。
x = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"
y = int(input("How many digits of Pi would you like to Print?"))
print(x[1:y+1])
您不能将整数用作列表。但是因为python的强大功能可以渲染字符串。还要关心变量名称。最后因为python从0开始计数到n,所以第n个数字必须是第n + 1个位置。