用于循环说明

rea*_*pie -3 c# for-loop

所以我一直试图弄清楚它是如何工作的,但我的书并不能很好地解释它.

有人可以解释一下为什么结果是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());
    }

}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 6

像这样迭代你的循环:

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
Run Code Online (Sandbox Code Playgroud)

如何解决:

i <= loopEnd
Run Code Online (Sandbox Code Playgroud)

然后它看起来像这样:

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.
Run Code Online (Sandbox Code Playgroud)