【问题标题】:Find the sum of even valued terms in the Fibonacci Sequence(Project Euler)在斐波那契数列中找到偶数项的总和(欧拉计划)
【发布时间】:2013-12-30 07:51:28
【问题描述】:

我正在尝试来自 Project Euler.net 的问题。我遇到的问题是这样的。

通过考虑斐波那契数列中值不超过四百万的项,求偶数项之和。

我想出了以下代码。

#include<iostream>
#include<cstdlib>
using namespace std;

int main() {
int a=1,b=1,c,sum=0;
    while(c<4000000)
    {
        c=a+b;
        if((c%2)==0)
        sum+=c;

        a=b;
        b=c;
    }
     cout<<sum;
    return 0;
}

返回的总和始终为zero。我查看了 StackOverflow 上的其他解决方案,但无法理解我的解决方案中的问题。任何帮助表示赞赏。

【问题讨论】:

    标签: c++ fibonacci


    【解决方案1】:

    在进入循环之前你还没有初始化c。如果它包含大于限制的内容,则循环不会执行,并且sum 将在循环终止后保持0

    【讨论】:

      【解决方案2】:

      公共类示例{

      public static void main(final String args[]) {
      
      
          // fibno me even terms
          int a = 0, b = 1;
          int temp = 0;
      
          // print fibo below 4 million
          for (int i = 0; i <= 4000000; i++) {
      
              int c = a + b;
      
              // System.out.println(c);
      
              if (c % 2 == 0)
      
              {
      
                  temp = temp + c;
      
      
                  // System.out.println("Even" + c);
              }
              a = b;
              b = c;
      
          }
      
          System.out.println("temp value is " + temp);
      
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-07
        • 1970-01-01
        • 2013-02-23
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多