gpt4 book ai didi

python - 根据python中的变量限制小数

转载 作者:太空宇宙 更新时间:2023-11-04 06:42:36 25 4
gpt4 key购买 nike

我正在尝试编写一个返回 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

关于python - 根据python中的变量限制小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28329021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com