为什么Progress Bar总是达到99%?

pan*_*ish 3 python python-2.7 python-3.x

我在python中为进度条编写了一个小程序.但是这个程序总是达到99%.始终存在1%的不准确度.以下是我的代码.

import time
import sys

for i in range(100):
    time.sleep(1)
    sys.stdout.write("\r%d%%" % i)
    percent = float(i)/100
    hashes = '#' * int(percent * 50)
    spaces = '-' * (50 - len(hashes))
    sys.stdout.write("\rPercent: [{0}] {1}%".format(hashes + spaces, int(percent * 100)))
    sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

在上述程序中,始终存在1%的不准确度.如果我将范围取为100然后计算%; 我的进度条保持在99%,如果范围是50,我的进度条保持在98%.任何人都可以告诉我,如果我在做错了吗?

Nho*_*hor 5

那是因为range(100)会输出一个列表[0, 1, ..., 99].你需要在range(101)这里使用.干杯!