c# - Why does the value of this variable go over 256 when I programmed it not to? -


here's code:

 public void button1_click(object sender, system.eventargs e)     {         system.random rnd = new system.random();         int ci = 1;             int di=1;                 int fi=1;         int c = rnd.next(1, 254);         int d = rnd.next(1, 254);                 (int f = rnd.next(1, 254); f < 255; f+=fi)                 {                      this.backcolor = system.drawing.color.fromargb(c, d, f);                     application.doevents();                     if (c == 254 || c == 0) { ci *= -1; }                     if (f == 254 || f == 0 || f == 50 || f == 100 || f == 150 || f == 200)                     {                         d += di;                     }                      if (d == 255 || d == 0)                     {                         di *= -1;                     }                     if (f==254|| f == 0)                     {                         fi *= -1;                     }                     if (d == 254)                     {                         c += ci;                     }                 }      } 

the error pops value of d goes on 256.

however, when run in debugger, can't see situation d go on 256. when d 255, di becomes negative therefore d += di decrease value of d. therefore impossible d ever go above 255. therefore confusing when debugger tells me d went 256.

can explain me why happens?

suppose f can never go above 254 in inner loop, , d 255.

the first time following code executed, di become negative. however, since innermost loop continues executing d has not changed, on next pass through innermost loop d still 255 condition sets di positive.

if (d == 255 || d == 0) {     di *= -1; } 

i believe following closer intended each of blocks containing variable *= -1; (i used d specifically):

if (d == 255) {     di = -1; } else if (d == 0) {     di = 1; } 

Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -