根据 python 中的变量限制小数
Limiting decimals according to variable in python
我正在尝试编写一个程序,使 returns 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
中的数字的方法。
将 precision/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
这是您尝试执行的替代方法:
print(round(ratio, 2))
上面的代码片段会将值 ratio
舍入到小数点后两位。所以要为小数整数做这件事,你可以这样做:
print(round(ratio, decimals))
我正在尝试编写一个程序,使 returns 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
中的数字的方法。
将 precision/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
这是您尝试执行的替代方法:
print(round(ratio, 2))
上面的代码片段会将值 ratio
舍入到小数点后两位。所以要为小数整数做这件事,你可以这样做:
print(round(ratio, decimals))