Python舍入混乱

2024-04-25 05:45:37 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码将1.5(值=15)舍入到2,但也将144.5(值=1445)舍入到144。我不明白为什么。你知道吗

def rounders(value):
    count = 0
    while value >= 10:
        value = round(value / 10, 0)
        count += 1
    return value * (10 ** count)

这是我试图解决代码战挑战“圆”。下面是一个正在尝试的解释。你知道吗

示例

对于值=15,输出应为 圆角(值)=20

对于值=1234,输出应为 圆角(值)=1000。你知道吗

1234->;1230->;1200->;1000。你知道吗

对于值=1445,输出应为 舍入(值)=2000。你知道吗

1445->;1450->;1500->;2000年。你知道吗


Tags: 代码gt示例returnvaluedefcount圆角
1条回答
网友
1楼 · 发布于 2024-04-25 05:45:37

这个问题非常类似于Strange behavior of numpy.round。关于np.round的内容直接适用于python3的内置round方法。请注意,python2的行为是不同的(如上面的文章所述)。感谢暗影游侠指出这点。)

看看round方法的documentation

If two multiples are equally close, rounding is done toward the even choice.

也就是说

round(2.5) == 2
round(3.5) == 4

您可以使用简单的if语句编写具有直观行为的舍入方法:

def myRound(x):
    r = x % 1
    if r < 0.5:
        return x-r
    else: 
        return x-r+1

相关问题 更多 >