【问题标题】:Rounding Off function to given decimal without using round function在不使用舍入函数的情况下将函数舍入到给定的小数
【发布时间】:2016-01-23 19:34:15
【问题描述】:

我正在尝试编写一个函数来将浮点数四舍五入到 n 位小数。该函数可以接受一个或两个参数。如果只有一个参数,则数字应四舍五入到小数点后两位。

这是我到目前为止所得到的:

def roundno(num,point=2):
    import math
    x=1*(math.pow(10,-point))
    round=0
    while (num>x):
            while(num>0):
                    round+=num/10
                    num=num/10
                    round*=10
            round+=num/10
            num=num/10
            round*=0.1
    return round

我每次都得到无穷大作为输出......我哪里出错了?

【问题讨论】:

    标签: python floating-point decimal rounding


    【解决方案1】:

    我看不出您的算法应该如何舍入数字。我想类似的策略可能会奏效,但是您需要在某个地方进行减法...

    这样做的一种方法是将参数转换为字符串,调整小数点后的位数,然后将字符串转换回浮点数,但我怀疑您的老师不会喜欢这种解决方案。 :)

    这是一种简单的算术舍入方法:

    def roundno(num, point=2):
        scale = 10.0 ** point
        return int(num * scale) / scale
    
    
    data = [123, 12.34, 1.234, 9.8765, 98.76543]
    
    for n in data:
        print n, roundno(n), roundno(n, 3)
    

    输出

    123 123.0 123.0
    12.34 12.34 12.34
    1.234 1.23 1.234
    9.8765 9.87 9.876
    98.76543 98.76 98.765
    

    这只会删除不需要的数字,但不难修改它以四舍五入或关闭(您的问题不清楚您想要哪种类型的四舍五入)。

    请注意,此函数不检查 point 参数。它确实应该检查它是否是一个非负整数,否则将引发 ValueError 并带有适当的错误消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      相关资源
      最近更新 更多