【问题标题】:How to limit the number of digits? [duplicate]如何限制位数? [复制]
【发布时间】:2018-02-17 15:59:50
【问题描述】:

在不使用任何库的情况下,我应该在我的代码中添加什么以返回值15.58

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

# return = 15.5885

【问题讨论】:

  • 也许您应该在代码中添加语言名称
  • 我的意思是python
  • 你的问题不清楚。您的意思是要将结果四舍五入到最接近的百分之一吗?你想要什么样的四舍五入——向上、向下、4/5、庄家/对称,或者你不在乎?您希望为您的示例提供哪个特定结果:15.5815.59?您是否需要准确的答案,或者通常的浮点值(这将非常接近您寻求的值但可能不完全等于它)就足够了?您是在谈论返回特定值还是将其打印以看起来特定的方式?
  • 当我使用时; def solution(side): result = (side**2)*(3**(0.5))/4 result = round(result,2) 返回结果它给出的结果为 15.59 实际上我想学习如何四舍五入和向下,但如果我们考虑这种情况,我希望它向下舍入
  • 请在 Python 中查找四舍五入。

标签: python function return digit


【解决方案1】:

原始结果值: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

【讨论】:

    【解决方案2】:
    def solution(side):
       result = (side**2)*(3**(0.5))/4
       return round(result,2)
    

    #return = 15.59

    【讨论】:

    • 我怎样才能把它四舍五入,我的意思是#return = 15.58
    • 不要只发布代码。请解释为什么这会回答这个问题。
    【解决方案3】:

    使用取整值:

    # 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
    

    【讨论】:

    • 查看更新答案以获得获得正确答案的最简单方法@theausome
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2017-01-23
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多