使用模数前进/减少功能

时间:2013-12-09 17:17:20

标签: function if-statement return modulo

我无法在编程中找到如何做到这一点。 我现在正在使用一种名为chuck的语言,但你可以用python帮助我。

我需要一个函数返回一个值,但同时调用该值前进或减少该值,它也需要保持在一定数量内(如模数)。我在这里解释代码:

variable named length = value 4

variable named play = value 0

function named advance
   return variable
   variable is advanced by one

function named goback
   return variable
   variable decrease by one

advance is called  --- return 0
advance is called  --- return 1
advance is called  --- return 2
advance is called  --- return 3
advance is called  --- return 0
decrease is called --- return 3
decrease is called --- return 2
decrease is called --- return 1
decrease is called --- return 0
decrease is called --- return 3

我希望很清楚,谢谢!

2 个答案:

答案 0 :(得分:1)

最简单的方法是在临时变量的帮助下。

length = 4
play = 0

def advance():
    tmp = play
    play = play + 1
    return (tmp % length)

def decrease():
    tmp = play
    play = play - 1
    return (tmp % length)

使用示例测试用例运行此代码应该会返回相同的值。我的Python有点生疏,所以语法可能不是100%准确,但概念就在那里。

答案 1 :(得分:0)

我不熟悉python或'chuck',但基于你的伪代码,你似乎想要这样的东西:

function named advance
    variable := variable + 1
    return (variable - 1) mod length

function named goback
    variable := variable - 1
    return (variable + 1) mod length

如果您需要variable始终保持在界限范围内,请在递减\ n递增之后取mod length