我正在寻找一种基于输入值循环遍历连续数字的解决方案。类似于模数,但对于负数不同。与下面低效的代码相比,是否有更好的解决方案?以下是一些输入/输出示例:
Numbers range 0 to 2
-2 -> 1
-1 -> 2
0 -> 0
1 -> 1
2 -> 2
3 -> 0
4 -> 1
//Inefficient Code example
int getConsecutiveVal(int min, int max, int input) //Inclusive in this scenario
{
while (input>max)
input -= (1+max-min);
while (input<min)
input += (1+max-min);
return input;
}
//Incorrect Code example since func(0,2,-1) returns 2
int getConsecutiveVal(int min, int max, int input)
{
return (input % (1+max-min))+min;
}
最佳答案
为了能够递增或递减,我使用了以下函数。它不止 1 行,但数学运算更少。它在精神上与原始海报的格式相似。测试了阳性和阴性病例。
int16_t cycleIncDec(int16_t x, int16_t dir, int16_t xmin, int16_t xmax) {
// inc/dec with constrained range
// the supplied xmax must be greater than xmin
x += dir;
if (x > xmax) x = xmin;
else if (x < xmin) x = xmax;
return x;
}
具有各种起始值和步长的 cycleIncDec() 输出
x: 11: +1 0 1 2 3 4 5 6 0 1 2 3
x: 4: -1 3 2 1 0 -1 -2 -3 -4 -5 -6 -7
x: -8: -1 -13 -12 -11 -10 -9 -8 -13 -12 -11 -10 -9
x:-190: -2 -192 -194 -196 -198 -200 -170 -172 -174 -176 -178 -180
关于c++ - 如何有效地循环连续数字c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27615050/