【问题标题】:I want to know the error in my code. This is to print sum of all even numbers till 1 to N我想知道我的代码中的错误。这是打印所有偶数的总和,直到 1 到 N
【发布时间】:2021-12-28 15:02:52
【问题描述】:
#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 的值,但前面没有打印任何内容。

【问题讨论】:

  • 一旦遇到第一个偶数i,您就不再增加i 而是永远循环。
  • if() 条件评估为true 时,您能否将手指指向循环内递增i 的确切行?附言无论如何,整个方法都是错误的。这是一个简单的数学公式。不需要循环来手动添加任何内容。这一定是来自无数网站之一的谜题,这些网站都有随机编码谜题列表,这些谜题依赖于数学技巧。如果你不知道诀窍是什么,生成的程序会因为耗时太长而失败,或者无法处理某些极端情况。
  • 无论如何,你甚至不需要循环来解决这个问题。您正在计算算术级数的总和;有一个封闭式公式。
  • 使用一些数学。和 1 + 2 + ... + N 是 N*(N+1)/2。偶数 2*1 + 2*2 + ... + 2*(N/2) 的和是 2 * (1 + 2 + ... + N/2)。
  • 如果你真的想使用循环,生成偶数而不是寻找它们:for (int i = 2; i &lt; n; i += 2) sum += i;

标签: c++ loops visual-c++ error-handling sum


【解决方案1】:

对于初学者来说,变量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;
}

【讨论】:

  • for循环更好的是n*(n+2)/4
  • @justANewbie 我认为作业的目的是调查循环。:)
【解决方案2】:
while(i<=N)
{
    if(i%2 == 0)
    {
        sum = sum + i;
    }
    else
    {
        i = i + 1;
    }
}

让我们一步一步来。想象一下,我们在i = 2 的循环中,您输入了N = 5。那样的话……

while(i <= N)

2

if(i%2 == 0)

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

sum = sum + i;

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

while(i <= N)

iN 都没有改变,所以 2

if(i%2 == 0)

2 % 2 == 0 依然为真,所以我们再次进入这个分支……


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

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

int sum = 0;

【讨论】:

  • 值得注意的是,sum 未初始化。
  • @justANewbie 不错。已编辑。
【解决方案3】:

当 i is even 因为你没有增加它时,你会无限循环。 如果您想使用该 while 循环,则更好的选择是:

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

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

【讨论】:

    【解决方案4】:

    不需要循环,如果需要也可以在编译时计算 sum

    // 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;
    }
    

    【讨论】:

      【解决方案5】:

      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++ 代码并运行它,它会解决你的问题。

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      【解决方案6】:

      您的程序存在 2 个问题

      错误 1

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

      未定义的行为意味着任何事情1都可能发生包括但不限于给出您预期输出的程序。但是永远不要依赖具有未定义行为的程序的输出。

      这就是为什么建议:

      始终在本地/块范围内初始化内置类型。

      错误 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,其中提到:对程序的行为没有限制。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-21
        • 2021-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-27
        • 1970-01-01
        相关资源
        最近更新 更多