Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# For循环解释_C#_For Loop - Fatal编程技术网

C# For循环解释

C# For循环解释,c#,for-loop,C#,For Loop,所以我一直想弄清楚它是如何工作的,但我的书并没有很好地解释它 有人能解释一下为什么结果是45吗?不是应该是55岁吗 这是我的代码&结果如下图所示 public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int l

所以我一直想弄清楚它是如何工作的,但我的书并没有很好地解释它

有人能解释一下为什么结果是45吗?不是应该是55岁吗

这是我的代码&结果如下图所示

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int loopStart;
        int loopEnd;
        int answer = 0;

        loopStart = int.Parse(textBox1.Text);
        loopEnd = int.Parse(textBox2.Text);

        //The code will keep running as long as End is bigger than start
        for (int i = loopStart; i < loopEnd; i++)
        {
            answer = answer + i;
        }
        MessageBox.Show(answer.ToString());
    }

}
您的循环终止于i
1+2+3+4+5+6+7+8+9=45

如果你想要得到你期望的答案,你必须说我你的代码在1到9之间执行。所有这些数字的总和是45

要使循环转到10,这似乎是您想要的,如果i为10,则条件需要返回true,因此:

for (int i = loopStart; i <= loopEnd; i++)
{
    answer = answer + i;
}
注意只需像这样迭代循环:

如何修复它:

然后看起来是这样的:


调试器非常适合整理这类内容。嗯,刚刚学习for循环的人可能还没有到达调试器章节!:请尽量提供最少的例子来说明问题。在这种情况下,使用硬编码值的循环比从控件读取值的完整WinForms程序要好得多。不要误用标记。这不是关于VisualStudio的问题;因为您是用C编写的,所以不要用Javascript标记。
loopStart = 1
loopEnd = 10
answer = 0

1<10 - 1
2<10 - 3
3<10 - 6
4<10 - 10
5<10 - 15
6<10 - 21
7<10 - 28
8<10 - 36
9<10 - 45
10<10 = false - You've declared that 10 have to be SMALLER than 10
i <= loopEnd
loopStart = 1
loopEnd = 10
answer = 0

1<=10 - 1
2<=10 - 3
3<=10 - 6
4<=10 - 10
5<=10 - 15
6<=10 - 21
7<=10 - 28
8<=10 - 36
9<=10 - 45
10<=10 = 55 - Yup it is SMALLER OR EQUAL than 10.