为什么循环在51之后继续?

时间:2014-05-14 16:54:50

标签: c# winforms

我有这个button4点击事件:

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;

因此,如果width是512数字10,则第一次迭代宽度将为502 并且最后宽度是2.但是然后它进行另一次迭代并且减去10使得宽度= -8 我使用了一个断点,我看到在第五十五个宽度为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);
            }

行路径= ...是:

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

我在这一行(宽度 - 数字)和(高度 - 数字)做了,我在此行之前已经做过。一旦我移除并只留下宽度和高度,它就能正常工作。不多了-8。 即使我从&#34; i&lt; = dirsnumbers&#34;到&#34; i&lt; dirsnumbers&#34;我得到-8

但现在它正在发挥作用。

1 个答案:

答案 0 :(得分:4)

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