循环交替增量

时间:2017-02-08 21:47:24

标签: loops for-loop math

我坚持如何制作一个将在一系列中交替增量的for循环。例如:

i          x
2.       7
3.       12
4.        14

其中x是i的某种组合。它首先递增5,然后递增2然后回到5.我尝试使用模数来启动交替序列,但我似乎无法使数字增加。有任何想法吗?谢谢。

2 个答案:

答案 0 :(得分:1)

它必须是for循环吗?还有while循环。

int i = 0;  
char switcher = 0; /*in this case ot could also be a bool.*/  
while(some statement)  
{  
    switch(switcher)  
    {  
    case 0:  
        i+=5;  
        break;  
    case 1:  
        i+=2;  
        break;  
    }  
    switcher++;  
    if(switcher > 1)  
        switcher = 0;  
     //do something  
}

您可以轻松地为该代码添加更多不同的增量。

答案 1 :(得分:0)

最好使用带有标志的while循环来跟踪你是否需要增加2或5。

incrementFlag = true;
while(someCondition)
{
   [code...]


   if (incrementFlag)
      i += 5;
   else
      i+=2

   incrementFlag = !incrementFlag; // Alternate incrementing
}
相关问题