python输入一个十进制整数,用户输入值用作十进制值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.

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'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值