如何限制位数?

How to limit the number of digits?

我应该在我的代码中添加什么来使 return 值 15.58,而不使用任何库?

def solution(side):
  result = (side**2)*(3**(0.5))/4
  return result

# return = 15.5885

使用舍入到上限值:

# First we take a float and convert it to a decimal
result = (side**2)*(3**(0.5))/4

# Then we round it to 2 places
output = round(result,2)
print output

您可以使用 math.floor 得到 15.58 :

import math
result = (math.floor(result * 100)) / 100.0// 15.58
def solution(side):
   result = (side**2)*(3**(0.5))/4
   return round(result,2)

# return = 15.59

原始结果值:15.5884572681

floor向下取整得到15.58:

import math
def solution(side): 
    result = (side**2)*(3**(0.5))/4 
    return math.floor(result*100)/100
print(solution(6))  # prints 15.58

使用 round 精确 2 得到 15.59:

def solution(side): 
    result = (side**2)*(3**(0.5))/4 
    return round(result,2)
print(solution(6))  # prints 15.59