Python 要用作十进制值的用户输入值

Python 要用作十进制值的用户输入值,python,expression,decimal,user-input,Python,Expression,Decimal,User Input,我正在编写一个python代码,其中我要求用户输入,然后我必须使用他们的输入来给出表达式答案的小数位数 userDecimals = raw_input (" Enter the number of decimal places you would like in the final answer: ") 然后我把它转换成整数值 userDecimals = int(userDecimals) 然后我编写表达式,我希望答案的小数位数与用户从UserDecimals输入的小数位数相同,我不知

我正在编写一个python代码,其中我要求用户输入,然后我必须使用他们的输入来给出表达式答案的小数位数

userDecimals = raw_input (" Enter the number of decimal places you would like in the final answer: ") 
然后我把它转换成整数值

userDecimals = int(userDecimals)
然后我编写表达式,我希望答案的小数位数与用户从UserDecimals输入的小数位数相同,我不知道如何实现这一点

表达式是

math.sqrt(1 - xx **2)

如果这还不够清楚,我将尝试更好地解释它,但我对python还不熟悉,我还不知道如何做很多事情。

格式化打印语句时,可以指定要显示的有效数字的数量。例如,
“%.2f”%float_值
将显示两位小数。有关更详细的讨论,请参阅

你想要这样的东西:

import math

xx = .2

userDecimals = raw_input (" Enter the number of decimal places you would lik    e in the final answer: ")
userDecimals = int(userDecimals)

fmt_str = "%."+str(userDecimals)+"f"

print fmt_str % math.sqrt(1 - xx **2)
产出:

Enter the number of decimal places you would like in the final answer: 5
0.97980

格式化打印语句时,可以指定要显示的有效数字数。例如,
“%.2f”%float_值
将显示两位小数。有关更详细的讨论,请参阅

你想要这样的东西:

import math

xx = .2

userDecimals = raw_input (" Enter the number of decimal places you would lik    e in the final answer: ")
userDecimals = int(userDecimals)

fmt_str = "%."+str(userDecimals)+"f"

print fmt_str % math.sqrt(1 - xx **2)
产出:

Enter the number of decimal places you would like in the final answer: 5
0.97980
使用并将
userDecimals
传递到以下部分的
precision
部分:

使用并将
userDecimals
传递到以下部分的
precision
部分: