我们怎样才能用重复的数字做无限循环
How can we make infinite loop with repeating numbers?
我做了一个数组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
}
}
相关文章:
- 过载'operator new'如何导致无限循环?
- 使用fstream对txt文件中的数字进行循环
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 为什么我的埃拉托色尼代码筛子无限循环.我已经用几个数字进行了测试
- 比较二维数组中的数字时的无限循环
- 输入验证,需要数字,而不是字符串.代码导致无限循环
- 我们怎样才能用重复的数字做无限循环
- C++猜数字游戏在其他计算机上崩溃并无限循环修复
- 猜数字 - 读取错误时无限循环
- 当输入字符串而期望输入数字时,使用cin进行无限循环