我们最初得到的提示符是创建一个函数,该函数接收一个数字作为参数,并返回该数字的日志四舍五入到4小数位。我需要函数以min_num和max_num作为参数
这是我的密码:
def min_num():
while True:
i = int(input("What's your minimum value?"))
if i > 0:
return i
print("ERROR. Minimum should be greater than 0")
def max_num(min_mum):
while True:
i = int(input("What's your maximum value?"))
if i > min_num:
return i
print(f"ERROR. Maximum value must be greater {min})")
min_value = min_num()
max_value = max_num(min_value)
发布于 2022-02-14 20:55:28
您可以使用Python的log
包附带的math
函数。
内置的round
函数将小数圈数作为第二个参数。round
比@alexpdev建议的Decimal
更容易出现错误,但我认为这对家庭作业来说不是问题。
import math
def rounded_log(num: float, number_of_decimals: int, base: int) -> float:
return round(
math.log(num, base),
number_of_decimals
)
发布于 2022-02-14 19:36:52
使用python附带的decimal
模块,您可以指定浮点数的精度。
import decimal
decimal.getcontext().prec=5
a = 1.65745678656
b = 2.4584583893
c = decimal.Decimal(a) + decimal.Decimal(b)
print(c)
输出为4.1159
对于数学函数,您可以尝试一些十进制对象的方法。例如:
import math
import decimal
decimal.getcontext().prec = 4
num = 3999 # randomly chosen number
flt = math.log(num) # uses math.log function
dec = decimal.Decimal(num) # turns num into a Decimal instance
dec = dec.ln() # uses the Decimal ln() method
# flt is 8.293799608846818
# dec is 8.294
# flt == dec (rounded to a precision of 4)
print(dec, flt)
输出为8.294 8.293799608846818
更多信息可以在模块的python文档中找到。https://docs.python.org/3/library/decimal.html
https://stackoverflow.com/questions/71120811
复制相似问题