在 C++ 中使用模算术(或)(%)运算符,我们可以循环遍历具有范围的连续数字。
例如:
如果范围是 5(或)模 5,那么我们可以循环遍历
0 1 2 3 4 0 (5) 1(6) 2(7) 3(8) 4(9) 0(10)............0 1 2 3 等
问题:
在类似的意义上,我们可以使用任何算术关系/C++技巧来在一定范围内向前移动增加的数字(直到上限)和反向移动(直到下限或0)的数字。
例如:
如果范围 = 5 那么
0 1 2 3 4 3 2 1 0 1 2 3 4 3 2 1 0 .....0 1 2 3 等
在下面的程序中,我使用了两种方法在给定范围内向前/向后迭代。
但我很感兴趣-有没有最好的方法(C++ 技巧/数学关系)在给定范围内迭代正向和反向?
#include<iostream>
int main() {
int range = 5;
// 0 1 2 3 4 0 1 2 3 4 .....(Cycle through in the range 0 - 4)
int i = 0;
while(true) {
// 0 1 2 3 4 0 1 2 3 4 .....(cycle through in the range 0 - 4)
std::cout<< i;
i = (i+1)% range; // Modulo
// some break condition
}
// 0 1 2 3 4 3 2 1 0 .......... (Forward and Reverse in the range 0 - 4)
// Method 1:
int j = 0;
bool reverse = false;
while(true) {
if(reverse == false) {
if(j < range) {
std::cout << j;
j = j+1;
}
else {
reverse = true;
j = j-1;
}
}
else {
j = j-1;
std::cout << j;
if(j == 0) {
reverse = false;
j = j + 1;
}
}
// some break condition
}
// 0 1 2 3 4 3 2 1 0 .......... (Forward and Reverse in the range 0 - 4)
// Method 2:
// Using modulo (if the range is big value then this is not good approach)
int limit[8] = {0,1,2,3,4,3,2,1};
int k = 0;
while(true) {
std::cout<< limit[k];
k = (k+1)%8;
// some break condition
}
return 0;
}