Fibonacci数的变化C ++

时间:2015-10-24 14:27:09

标签: c++ visual-studio-2010 fibonacci variance standard-deviation

你好我写了一个c ++程序来计算Fibonacci数。 基本上我希望我的程序计算让我们说例如10个Fibonacci数,然后计算它们的方差和标准差。目前我设法得到计算斐波那契数字,但我不知道如何直接加载这些数字来计算方差和标准差。所以我要求输入它们并将它们保存在数组x中,然后我计算方差和标准差。

#include <conio.h>
#include <iostream>
#include <windows.h>
#include <math.h>
using namespace std;

int n,i,one=0,two=1,ne;
//one -> first number
//two -> second number
//ne -> next number
float x[100], sum=0, avg, vari=0, vari2, sd;

int main()
{ 
   cout << "Enter how many Fibonacci numbers you want\n" << endl;
   cin >> n;

   cout << "\nFirst " << n << " Fibonacci numbers are : " << endl;

   for ( i=0 ; i<n ; i++ )
   {
      if ( i<=1 )
         ne=i;
      else
      {
         ne=one+two;
         one=two;
         two=ne;
      }
      cout << ne << endl;  
   }

   for (i=0; i<n; i++)
   {
       cout << "Input your Fibonacci numbers  ";
       cin >> x[i];

       sum = sum + x[i];      
   }  
       avg = sum/n;  

       for (i=0; i<n; i++)
       {
               vari = vari + pow((x[i] - avg),2);
       }

       vari2 = vari/n;
       sd = sqrt(vari2);

   cout << "The sum of the numbers: " << sum << endl;
   cout << "The average of the numbers: " << avg << endl;
   cout << "The variance of the numbers: " << vari2 << endl;
   cout << "The standard deviation of the numbers: " << sd << endl;


   _getch();   
} 

这是新代码: 除了差异之外,一切都运作良好。 我不知道为什么方差计算不正确。

#include <conio.h>     #include <iostream>
#include <windows.h>
#include <math.h>
using namespace std;

int n,i,one=0,two=1,ne;
//one -> first number
//two -> second number
//ne -> next number
float x[10000], sum=0, avg, vari=0, vari2, sd;

int main()
{ 
   cout << "Enter how many Fibonacci numbers you want\n" << endl;
   cin >> n;

   cout << "\nFirst " << n << " Fibonacci numbers are : " << endl;

   for ( i=0 ; i<n ; i++ )
   {
      if ( i<=1 )
         ne=i;

      else
      {
         ne=one+two;
         one=two;
         two=ne;
      }

      cout << ne << endl; 
      sum = sum + ne;
      avg = sum/n;

   }




       for (i=0; i<n; i++)
       {
               vari = vari + pow((x[i] - avg),2);
       }

       vari2 = vari/n;
       sd = sqrt(vari2);

   cout << "The sum of the numbers: " << sum << endl;
   cout << "The average of the numbers: " << avg << endl;
   cout << "The variance of the numbers: " << vari2 << endl;
   cout << "The standard deviation of the numbers: " << sd << endl;


   _getch();   
} 

1 个答案:

答案 0 :(得分:0)

无需为sum和average创建for循环,它们的代码可以在第一个循环中实现:

for ( i=0 ; i<n ; i++ )
{
    if ( i<=1 )
        ne=i;
    else
    {
        ne=one+two;
        one=two;
        two=ne;
    }
    cout << ne << endl;
    sum = sum + ne;
    avg = sum/n;

现在对于variance和sd,您可以为每个函数创建一个函数来计算它们的值:

double funcvari(double d){

    vari = vari + pow((ne - d),2);
    vari2 = vari/n;


return vari2;
}

double funcsd(double fd){
sd = sqrt(fd);
return sd;
}

Live Demo