C++ 我们如何用重复的数字做无限循环?

C++ 我们如何用重复的数字做无限循环?,c++,arrays,algorithm,C++,Arrays,Algorithm,我制作了一个数组intspriteanimationright[3]={0136272}我希望这些数字重复如下: 0 136 272 0 136 272 .. .. 我们如何才能做到这一点?使用模: int spriteAnimationRight[3] = {0, 136, 272}; for (auto i = 0; ; i++) { printf("%d\n", spriteAnimationRight[i%3]); } 您可以执行以下操作 whil

我制作了一个数组
intspriteanimationright[3]={0136272}我希望这些数字重复如下:

0  
136  
272  
0  
136  
272  
..  
..
我们如何才能做到这一点?

使用模:

int spriteAnimationRight[3] = {0, 136, 272};
for (auto i = 0; ; i++) {
    printf("%d\n", spriteAnimationRight[i%3]);
}

您可以执行以下操作

while(1)
{
   cout<<spriteAnimationRight[0];
   cout<<spriteAnimationRight[1];
   cout<<spriteAnimationRight[2];
}
while(1)
{
cout您可以使用运算符:

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

#包括
使用名称空间std;
int main()
{
int指数=0;
int-spriteAnimationRight[3]={0136272};
而(1)
{
如果(索引==3)
{/*当index=3时,将其重新设置为第一个索引*/
指数=0;
}

你打算用它吗?现在只需在cmd上打印它。但以后用于精灵动画。我非常喜欢这样:)最简单:DDo你有使用SFML的经验吗?不,我没有使用SFML的经验当它返回到0时,我们可能会跳过我们需要的三件事之一。@Henrik否。
I
不会是3,因为如果它是3,我会将它设置为0.你能再解释一下为什么你认为我会有这个吗@ᴍ阿伦ᴍ在你使用它之后,你将3设置为0,但是你使用mod,所以你将有0,1,2,0,0,1,2,…但是它必须精确地达到3。当然,在这个小例子中,它显然是这样的。但是可能有这样的情况,循环更复杂,有更多的行可能修改
i
。或者
i
不是一个整数,而是一个整数一个double,当它到达一个边界时,你想重置它(或者当然,它不会被用作数组索引)。所以我更喜欢
=
,因为它在更复杂的情况下更健壮。这很好,直到计数器溢出并给出未定义的行为。
I=(I+1)%3
可能是一个更好的选择。它不会溢出,因为大多数编译器上的auto i变为无符号int。当它环绕时,它只会返回到0。不,
auto
将从
0
的类型推断
int
。即使它是无符号的,当它环绕到0时,也会得到错误的值(模3)。
int i = 0;
while(1) {
   if(i == 3) i = 0;  //preventing overflow
   cout<<spriteAnimationRight[i % 3];
   i++;
}
0 % 3  → 0
1 % 3  → 1
2 % 3  → 2
0 % 3  → 0
1 % 3  → 1
2 % 3  → 2
..
..
#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
    }
}