为什么51年后循环还在继续

本文关键字:继续 循环 51年 为什么 | 更新日期: 2023-09-27 18:03:26

我有这个button4 click事件:

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();
        }

这是变量的值:

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

现在我在dirsnumbers上循环,并且在行上使用了一个断点:

width = width - numeric;

所以如果宽度是512数字10,那么第一次迭代的宽度将是502最后宽度是2。然后再做一次迭代,让- 10,所以宽度= -8我使用了一个断点,我看到在迭代51的宽度是2,所以为什么它做另一个迭代,使宽度-8 ?

编辑* *

正在运行:

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);
            }

line path =…是:

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

我在这一行做了(width - numeric)和(height - numeric),我已经在这一行之前做了。一旦我删除,只留下宽度和高度,它的工作。没有-8了。即使我将循环从"i <= dirsnumbers"更改为"i

为什么51年后循环还在继续

您的循环运行52次,因为您使用<=而不是<。使用i < dirsnumbers或从1启动i