简体   繁体   English

用户输入值用作十进制值python

[英]user input value to use as decimal value python

I am writing a python code where I ask the user for input and then I have to use their input to give the number of decimal places for the answer to an expression. 我正在编写一个python代码,要求用户输入,然后必须使用他们的输入来给出表达式答案的小数位数。

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

then I convert this to integer value 然后我将其转换为整数值

userDecimals = int(userDecimals)

then I write the expression, and I want the answer to have as many decimal places as the user input from UserDecimals, and I don't know how to accomplish this. 然后我编写表达式,我希望答案的位数与UserDecimals的用户输入一样多,而我不知道该如何完成。

The expression is 表达式是

math.sqrt(1 - xx **2)

If this isn't clear enough I will try to explain it better, but I am new to python, and I don't know how to do a lot yet. 如果这还不够清楚,我将尝试更好地进行解释,但是我是python的新手,我还不知道该怎么做。

Use string formatting and pass userDecimals to the precision part of the format specifier : 使用字符串格式并将userDecimals传递给格式说明符precision部分:

>>> 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'

When formatting your print statement you can specify the number of significant figures to display. 格式化打印语句时,可以指定要显示的有效数字的数量。 For example '%.2f' % float_value will display two decimal places. 例如'%.2f' % float_value将显示两位小数。 See this question for a more detailed discussion. 请参阅此问题以进行更详细的讨论。

You want something like this: 您想要这样的东西:

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)

Outputs: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM