为什么我的代码不使用while循环返回总和?

时间:2018-10-25 01:16:54

标签: c# while-loop sum

我正在尝试查找(1到n)或给定数字的总和。 使用此代码:

        int n;
        int counter = 0;
        int sum = 0;

        Console.Write("Please enter the sum limit number: ");
        n = int.Parse(Console.ReadLine());

        //around here is where code freezes and nothing else happens 
        while(counter <=  n)
        {
            counter = +1;
            sum = sum + counter;
        }

        Console.Write("The sum from 1 - " + n + " =" + sum);

我知道我可以使用:

        int n;
        int counter = 0;
        int sum = 0;

        Console.Write("Please enter the sum limit number: ");
        n = int.Parse(Console.ReadLine());

        var sum = Enumerable.Range(1, n);

        Console.Write("The sum from 1 - " + n + " =" + sum.Sum());

但是我的下一个挑战是仅添加可被3或5整除的数字,因此我打算这样做:

        if (sum % 3 == 0 | sum % 5 == 0)
        { 
         total = total + sum;
        }

我的方法有什么问题?此外,实现此目的的其他方法也值得赞赏!

2 个答案:

答案 0 :(得分:1)

要退出while循环,需要满足条件。首先,需要在while循环中存在递增计数器。

要递增计数器变量,您可以尝试counter++/++counter(即后/前递增运算符),也可以执行counter += 1/ counter = counter + 1.

类似

    //around here is where code freezes and nothing else happens 
    while(counter <=  n)
    {
        counter += 1;  // not counter=+1;
        sum = sum + counter;
    }

参考:Increment decrement in C#

答案 1 :(得分:0)

如果要增加计数器,则应使用

counter = counter + 1;

counter++;

counter += 1;