python
  • python-2.7
  • python-3.x
  • 2015-11-06 38 views 3 likes 
    3

    我写了一个python进度条的小程序。但是这个程序总是保持在99%。总有一个不准确的1%。以下是我的代码。为什么Progress Bar始终保持在99%?

    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() 
    

    在上面的程序中总是有1%的不准确性。如果我将范围设为100,然后计算%;我的进度条卡在99%,如果范围是50,我的进度条卡在98%。任何人都可以告诉我,如果我在这里做错了什么?

    回答

    5

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

    相关问题