Question

I have this button4 click event:

private void button4_Click(object sender, EventArgs e)
        {
            string mainpath = Path.Combine(@"c:\temp\newimages",
                   "Changed_Resolution_By_" + numeric.ToString());
            Directory.CreateDirectory(mainpath);
            Image img = Image.FromFile(previewFileName);
            int width = img.Width;
            int height = img.Height;
            double res = width / numeric;
            dirsnumbers = (int)Math.Floor(res);
            for (int i = 0; i <= dirsnumbers; i++)
            {
                width = width - numeric;
                height = height - numeric;
                path = Path.Combine(mainpath,
        String.Concat("SecondProcess_", DateTime.Now.ToString("MMddyyyy-HHmmss")) +
                     "-" + "Width = " + (width - numeric) + " Height = " + (height - numeric));
                if ((width - numeric) > 0)
                {
                    Directory.CreateDirectory(path);
                }
            }
            backgroundWorker2.RunWorkerAsync();
        }

This is the variables values:

dirsnumbers after using Math.Floor = 51
numeric = 10
width = 512
height = 512

Now i loop over dirsnumbers and i used a breakpoint on the line:

width = width - numeric;

So if width is 512 numeric 10 then first itertion width will be 502 And in the end width is 2. But then it's doing another itertion and make minus 10 so width = -8 I used a breakpoint and i saw that on itertion 51 width was 2 so why it's doing another itertion and make width -8 ?

EDIT**

This is working:

for (int i = 0; i < dirsnumbers; i++)
            {
                width = width - numeric;
                height = height - numeric;
                path = Path.Combine(mainpath,
        String.Concat("SecondProcess_", DateTime.Now.ToString("MMddyyyy-HHmmss")) +
                     "-" + "Width = " + (width) + " Height = " + (height));
                Directory.CreateDirectory(path);
            }

The line path = ... was:

path = Path.Combine(mainpath,
            String.Concat("SecondProcess_", DateTime.Now.ToString("MMddyyyy-HHmmss")) +
                         "-" + "Width = " + (width - numeric) + " Height = " + (height - numeric));

I did in this line ( width - numeric) and also (height - numeric) and i did that already above before this line. Once i remove and left only width and height it's working. No more -8 . Even when i changed the loop from "i <= dirsnumbers" to "i < dirsnumbers" i got -8

But now it's working.

Was it helpful?

Solution

Your loop runs for 52 times because you are using <= instead of <. Use i < dirsnumbers or start i from 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top