我们怎样才能用重复的数字做无限循环

How can we make infinite loop with repeating numbers?

本文关键字:数字 无限循环 我们      更新时间:2023-10-16

我做了一个数组int spriteAnimationRight[3] = {0, 136, 272};我希望这些数字像下面这样重复:

0  
136  
272  
0  
136  
272  
..  
..

我们该怎么做?

您可以执行以下操作

while(1)
{
   cout<<spriteAnimationRight[0];
   cout<<spriteAnimationRight[1];
   cout<<spriteAnimationRight[2];
}

使用模数:

int spriteAnimationRight[3] = {0, 136, 272};
for (auto i = 0; ; i++) {
    printf("%dn", spriteAnimationRight[i%3]);
}
int i=0;
while(1)
{
    DoSomething(spriteAnimationRight[i]);
    i++;
    if(i >= 3) i = 0;
}

您可以使用取模运算符:

int i = 0;
while(1) {
   if(i == 3) i = 0;  //preventing overflow
   cout<<spriteAnimationRight[i % 3];
   i++;
}

为什么会这样?

取模运算符找到一个数除以另一个1 的余数。

0 % 3  → 0
1 % 3  → 1
2 % 3  → 2
0 % 3  → 0
1 % 3  → 1
2 % 3  → 2
..
..

1 http://en.wikipedia.org/wiki/Modulo_operation

#include <iostream>
using namespace std;
int main()
{
    int index=0;
    int spriteAnimationRight[3] = {0, 136, 272};
    while(1)
    {
         if(index==3)
         {/*when index=3, resset it to first index*/
          index=0;
         }
          cout<<spriteAnimationRight[index]<<endl; 
          index++;    
    }
}

如果你想清楚地看到输出,那么你需要在每个输出中创建一些延迟,为此你可以像这样做一个函数延迟。

#include <iostream>
using namespace std;
void delay()//to see output clearly you can make a sleep function
{
 /*this fucntion uses empty for loops to create delay*/
     for(int i=0;i<7000;i++)
     {
          for(int j=0;j<7000;j++)
          {
          }
     }
}
int main()
{
    int index=0;
    int spriteAnimationRight[3] = {0, 136, 272};
    while(1)
    {
         if(index==3)
         {/*when index=3, resset it to first index*/
          index=0;
         }
          cout<<spriteAnimationRight[index]<<endl; 
          index++; 
          delay();//for creating delay
    }
}