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

2024-10-01 19:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

然后我把它转换成整数值

^{pr2}$

然后我编写表达式,我希望答案的小数位数与用户从UserDecimals输入的一样多,但我不知道如何实现这一点。在

表达式是

math.sqrt(1 - xx **2)

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


Tags: ofthe答案代码用户younumberinput
2条回答

格式化打印语句时,可以指定要显示的有效数字的数目。例如,'%.2f' % float_value将显示两个小数位。有关更详细的讨论,请参见this question。在

你想要这样的东西:

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)

输出:

^{pr2}$

使用string formatting并将userDecimals传递给format specifierprecision部分:

>>> import math
>>> userDecimals = 6
>>> '{:.{}f}'.format(math.sqrt(1 - .1 **2), userDecimals)
'0.994987'
>>> userDecimals = 10
>>> '{:.{}f}'.format(math.sqrt(1 - .1 **2), userDecimals)
'0.9949874371'

相关问题 更多 >

    热门问题