用于循环说明

时间:2014-09-17 00:28:24

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

}

enter image description here

4 个答案:

答案 0 :(得分: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

如何修复:

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.

答案 1 :(得分:2)

您的代码执行1到9(含)之间。所有这些数字的总和是45。

要使循环转到10(这似乎是你想要的),条件需要在i为10时返回true,因此:

for (int i = loopStart; i <= loopEnd; i++)
{
    answer = answer + i;
}

注意<=“小于或等于”,而不是“严格小于”。

答案 2 :(得分:0)

你的循环终止于i < loopEnd,所以它永远不会在i = 10的情况下执行它。

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

答案 3 :(得分:0)

如果你想要你想要的答案,你必须说i&lt; = loopEnd而不是&lt; ......