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.
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.
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.
解决方案
Use string formatting and pass userDecimals to the precision part of the format specifier:
>>> 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'
博主编写Python代码,需根据用户输入的十进制整数确定表达式结果的小数位数。表达式为math.sqrt(1 - xx **2),但不知如何实现。解决方案是使用字符串格式化,将用户输入的小数位数传递给格式说明符的精度部分。
1410

被折叠的 条评论
为什么被折叠?



