我正在尝试编写一个返回 golden ratio 的程序最多小数位。 我到目前为止是这样的:
def gr(n):
a, b = 0, 1
for x in range(0, n):
a, b = b, a+b
else:
return(a)
decimals = int(input("What amount of decimals do you want to see of the golden ratio?"))
ratio = gr(41)/gr(40)
print(format(ratio, '2f'))
问题是我找不到一种方法来将ratio 格式化为decimals 中的数字。
请您参考如下方法:
将精度/小数变量传递给 str.format:
decimals = int(input("What amount of decimals do you want to see of the golden ratio?"))
ratio = gr(41)/gr(40)
print("{:.{}f}".format(ratio,decimals))
例子:
In [3]: decimals = int(input("What amount of decimals do you want to see of the golden ratio?"))
What amount of decimals do you want to see of the golden ratio?5
In [4]: ratio = gr(41)/gr(40)
In [5]: print("{:.{}f}".format(ratio,decimals))
1.61803
