【问题标题】:fibonacci sequence sum total error斐波那契数列总和误差
【发布时间】:2015-09-22 14:10:54
【问题描述】:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{   
    int last;

do{
    system("cls");
    cout<<"                              FIBONACCI                         "<<endl;
    int a,sum;
    cout<<"Enter the number of outputs you want to be displayed : ";
    cin>>a;

    long long unsigned int b= 0, c=1;
    while(a >=0)
    {
            cout<<b<<endl;
            sum+=b;
            b=b+c;
            c=b-c;
            a--;                        
    }
    cout<<"total = "<<sum<<endl;
    cin>>last;
}
while(last==0);

system("pause");
return 0;   
}

每当我想通过将 0 作为最后一个输入来重复它时,sum 的值不会自行重置,新的总和会添加到前一个总和中,并且错误的值会显示为总数。

【问题讨论】:

  • 添加语言标签可能会有所帮助...
  • 提示:代码越多空格越清晰:b = b + c;
  • @Satwik :如果其中一个答案可以帮助您修复代码,请不要忘记接受它;)

标签: c++ fibonacci


【解决方案1】:

您的变量 sum 在您访问它之前未初始化。

你应该改变

int a,sum;

int a;
int sum = 0;

【讨论】:

    【解决方案2】:

    您错误地声明了sum,它应该与bc 的类型相同

    long long unsigned int sum;
    

    sum 也未初始化,但是:你的计算很奇怪

    sum+=b;
    b=b+c;
    c=b-c;
    

    所以我推荐

    sum = c + b;
    b = c;
    c = sum;
    

    【讨论】:

      【解决方案3】:
      #include <iostream>
      #include <math.h>
      using namespace std;
      int main()
      {   
          int last;
      
      do{
          system("cls");
          cout<<"FIBONACCI \n\n";      
          int a,sum;
          cout<<"Enter the number of outputs you want to be displayed : ";
          cin>>a;
      
          long long unsigned int sum=0,b=0,c=1,d=0;
          while(a >=0)
          {
                  cout<<b<<endl;
                  sum+=b;
                  b=d+c;
                  c=d;
                  d=b;
                  a--;                        
          }
          cout<<"total = "<<sum<<endl;
          cin>>last;
      }
      while(last==0);
      
      system("pause");
      return 0;   
      }
      

      在计算中进行了更改,并且在 do..while 循环的请求中将 sum 初始化为零,抱歉标点符号错误

      【讨论】:

        猜你喜欢
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        • 2015-06-05
        • 1970-01-01
        • 1970-01-01
        • 2017-05-08
        相关资源
        最近更新 更多