代码之家  ›  专栏  ›  技术社区  ›  user1869582

除了在python中使用mod“%”之外,还有其他方法吗

  •  -1
  • user1869582  · 技术社区  · 7 年前

    例如

    maxNum = 3.0 
    steps = 5
    increment = 0
    time = 10
    while increment < time:
        print increment * (maxNum / steps)% maxNum
        increment+=1
    

    我把它作为输出

    0.0
    0.6
    1.2
    1.8
    2.4
    0.0
    

    但我想要3.0作为最大值,从0.0开始。

    0.0
    0.6
    1.2
    1.8
    2.4
    3.0
    0.0
    

    注意,对于计算部分,我必须避免逻辑循环。

    3 回复  |  直到 7 年前
        1
  •  0
  •   MBo    7 年前

    只有很小的变化起到了作用:

    maxNum = 3.0
    steps = 5
    i = 0
    times = 10
    step = maxNum / steps
    while (i < times):
        print(step * (i % (steps + 1)))
        i += 1
    
    0.0
    0.6
    1.2
    1.7999999999999998
    2.4
    3.0
    0.0
    0.6
    1.2
    1.7999999999999998
    
        2
  •  1
  •   John Coleman    7 年前

    itertools.cycle 要在它们之间循环:

    import itertools
    nums  = itertools.cycle(0.6*i for i in range(6))
    for t in range(10):
        print(next(nums))
    

    输出:

    0.0
    0.6
    1.2
    1.7999999999999998
    2.4
    3.0
    0.0
    0.6
    1.2
    1.7999999999999998
    
        3
  •  0
  •   vash_the_stampede    7 年前

    你可以做一个 if 如果下一个打印的数字是 0.0 然后打印 maxNum

    maxNum = 3.0
    steps = 5
    increment = 0
    time = 10
    
    while increment < time:
        print(round(increment * (maxNum / steps)% maxNum, 2))
        increment+=1
        if (round(increment * (maxNum / steps)% maxNum, 2)) == 0.0:
            print(maxNum)
    
    0.0
    0.6
    1.2
    1.8
    2.4
    3.0
    0.0
    0.6
    1.2
    1.8
    2.4
    3.0
    
    推荐文章