开发者

Get every 100th value in a loop

Is there a way to make this cleaner and not use the tempvalue like i have done here?


UPDATE the code had a logic bug and didn't show what I'm doing. This is what I'm doing:

var loopTempValue = noOfPackets / 100;
for(i=0; i 开发者_开发问答< noOfPackets; i++)
{   
    \\DoStuff

    if (i == loopTempValue)
    {
         loopTempValue = loopTempValue + (noOfPackets / 100);
         UploadBackGroundWorker.ReportProgress(pross);
    }
}

UPDATE Final

This is how its fixed after the feedback, thx guys.

if (i % (noOfPackets / 100) == 0 && i != 0)
{
     UploadBackGroundWorker.ReportProgress(pross);
}


if (i % 100 == 0 && i != 0) { //YOUR CODE }

Modulus is fantastic for checks like this.

More on Modulus - http://www.vias.org/cppcourse/chap04_01.html

UPDATE: I added && i != 0 for the 0 case being true.

If you want to use the tempvalue instead of hard coding 100, then this would be a solution:

if (i % tempvalue == 0 && i != 0) { //YOUR CODE }


You mean that you want the condition to be triggered 100 times during the loop, i.e. every 36th iteration? (In your original code you double the tempvalue each time, so it would only trigger seven times during the loop.)

You can use the modulo operator to check for that. This will trigger the condition at the last of each set of 36 iterations:

for(i=0; i < 3600; i++) {
   \\DoStuff

   if(i % 36 == 35) {
      \\DoStuff
   }
}


if( (i+1 % (tempvalue+1) == 0)
{
      //DoStuff

      //tempvaule = tempvalue + tempvalue;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜