我想知道我的代码中的错误。这是打印所有偶数的总和,直到 1 到 N

I want to know the error in my code. This is to print sum of all even numbers till 1 to N

#include<iostream>
using namespace std;

int main(){
    int i = 1;
    int sum;
    int N;
    cout << "Enter a number N: ";
    cin >> N;
    while(i<=N)
    {
        if(i%2 == 0)
        {
            sum = sum + i;
        }
        else
        {
            i = i + 1;
        }
    }
    cout << sum;
}

这是打印所有偶数的和,直到1到N。

当我尝试 运行 代码时,系统询问我 N 的值,但前面没有打印任何内容。

对于初学者来说,变量 sum 没有被初始化。

其次,当它是偶数时,您还需要增加变量 i。所以循环应该至少看起来像

while(i<=N)
{
    if(i%2 == 0)
    {
        sum = sum + i;
    }
    i = i + 1;
}

一般来说,最好在使用变量的最小范围内声明变量。

因此,最好使用 for 循环代替 while 循环,例如

for ( int i = 1; i++ < N; ++i )
{
    if ( i % 2 == 0 ) sum += i;
}
while(i<=N)
{
    if(i%2 == 0)
    {
        sum = sum + i;
    }
    else
    {
        i = i + 1;
    }
}

让我们逐步完成。假设我们在 i = 2 的循环中,而您输入了 N = 5。那样的话...

while(i <= N)

2 <= 5 为真,所以我们循环

if(i%2 == 0)

2 % 2 == 0 为真,所以我们进入这个分支

sum = sum + i;

更新总和,然后返回循环顶部

while(i <= N)

iN 都没有改变,所以 2 <= 5 仍然成立。我们仍然循环

if(i%2 == 0)

2 % 2 == 0 仍然成立,所以我们再次进入这个分支...


你看到这里发生了什么吗?由于 iN 都没有更新,您将继续进入同一个分支并无限循环。你能想出一种方法来防止这种情况发生吗?需要改变什么?

另请注意,int sum; 意味着 sum 将具有垃圾值(未初始化)。如果您希望它从 0 开始,您需要将其更改为

int sum = 0;

不需要循环,如果需要也可以在编译时求和

// use unsigned, the whole excercise is pointless for negative numbers
// use const parameter, is not intended to be changed
// constexpr is not needed, but allows for compile time evaluation (constexpr all the things)
// return type can be automatically deduced
constexpr auto sum_of_even_numbers_smaller_then(const unsigned int n)
{
    unsigned int m = (n / 2);
    return m * (m + 1);
}

int main()
{
    // compile time checking of the function
    static_assert(sum_of_even_numbers_smaller_then(0) == 0);
    static_assert(sum_of_even_numbers_smaller_then(1) == 0);
    static_assert(sum_of_even_numbers_smaller_then(2) == 2);
    static_assert(sum_of_even_numbers_smaller_then(3) == 2);
    static_assert(sum_of_even_numbers_smaller_then(7) == 12);
    static_assert(sum_of_even_numbers_smaller_then(8) == 20);

    return 0;
}

当 i 为偶数时你无限循环,因为你不增加它。 如果您想使用 while 循环,更好的选择是:

while(i<=N)
    {
       if(i%2 == 0)
            sum = sum + i;
       
       i=i+1;
    }
    cout << sum;

如果条件为假时不需要做任何事情,就不要使用 else。

int main(){

int input;                  //stores the user entered number
int sum=0;                  //stroes the sum of all even numbers
repeat:
cout<<"Please enter any integer bigger than one: ";
cin>>input;
if(input<1)                 //this check the number to be bigger than one means must be positive integer.
    goto repeat;            // if the user enter the number less than one it is repeating the entry.
for(int i=input; i>0; i--){ // find all even number from your number till one and than totals it.
    if(i%2==0){
        sum=sum+i;
        int j=0;
        j=j+1;
        cout<<"Number is: "<<i<<endl;
    }
}
cout<<endl<<"The sum of all even numbers is: "<<sum<<endl;}

复制此 C++ 代码并运行它,它将解决您的问题。

您的程序有 2 个问题

错误 1

变量 sum 尚未初始化。这意味着它有(持有)一个不确定的值。像你写 sum = sum + i; 时那样使用这个未初始化的变量是 未定义的行为 .

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has undefined behavior.

这就是为什么建议:

always initialize built in types in local/block scope.

错误 2

第二个问题是您没有更新变量i的值。

解决方案

您可以按如下所示解决这些问题:

int main(){
    int i = 1;
    int sum = 0; //INITIALIZE variable sum to 0
    int N;
    cout << "Enter a number N: ";
    cin >> N;
    while(i<=N)
    {
        if(i%2 == 0)
        {
            sum = sum + i;
        }
        
        i = i + 1; //update(increase i)
       
    }
    cout << sum;
}

1有关未定义行为的更多阅读(技术定义),您可以参考 undefined behavior's documentation 其中提到:程序的行为没有限制。