问题描述
我正在尝试添加数字,但要保持在一定范围内。如果它越过边界或越过边界,它将绕回另一个边界。
示例:
最小值:10 最多:50
- 20 + 10 = 30
- 20 + 30 = 50(或0 idrk)
- 20 + 31 = 1
- 40 + 20 = 10
- 40 + 70 = 10
- 40-10 = 30
- 10-30 = 30
- 10-20 = 40
- 10-70 = 40
我正在寻找两个函数,一个要加,一个要减。我并不在乎哪种语言,但首选python或java。感谢您的帮助!
解决方法
恐怕我们必须为您的问题添加更多具体信息:
- 边界是包容性的还是排他性的?
- 我们是在谈论整数还是浮点数?
如果您想将例程用作多种用途的库函数,则最好将一端定义为包含,而将另一端定义为排斥。
以下(不完整的)Java程序显示了解决的方向以及边界问题:只要碰到边界,它就会翻转到值框架的另一端:
public class FramedAddSub {
int min;
int max;
int value;
public FramedAddSub(int min,int max,int value) {
this.min = min;
this.max = max;
this.value = value;
}
public FramedAddSub add(int toAdd) {
final int diff = max - min;
if (toAdd >= 0) {
// step 1: norm to zero
value -= min;
// step 2: rest of division
value = (value + toAdd) % diff;
// step 3: re-norm to old offset
value += min;
} else {
// step 1: norm to zero from other end
value -= max;
// step 2:
value = (value + toAdd) % diff;
// step 3: re-norm back
value += max;
}
return this;
}
public static void main(String[] args) {
FramedAddSub test = new FramedAddSub(20,50,20);
System.out.println("start: " + test.value);
test.add(10);
System.out.println("+10: " + test.value);
test.add(20);
System.out.println("+20: " + test.value);
test.add(1);
System.out.println("+1: " + test.value);
test.add(30);
System.out.println("+30 should just turn around circle: " + test.value);
test.add(-1);
System.out.println("-1: " + test.value);
test.add(-1);
System.out.println("-1: " + test.value);
test.add(-30);
System.out.println("-30 should just turn around circle: " + test.value);
}
}
,
在python中尝试:
ans = abs(a + b) % 50
如果要进行减法运算,则需要将a
和b
传递为负数。
# define the range
start = 0
end = 93
# this function accepts positive and negative numbers in x
def mover(current_place,x):
locate = current_place + x
locate = locate % (end-start) # if x > the range
if locate > end:
locate = locate - end
if locate < start:
locate = locate + end
return locate
if __name__ == "__main__":
current_place = 50
print(current_place) #50
current_place = mover(current_place,10)
print(current_place) #60
current_place = mover(current_place,-20)
print(current_place) #40
current_place = mover(current_place,-50)
print(current_place) #83
current_place = mover(current_place,220)
print(current_place) #24