斐波那契数的方差



你好,我写了一个c++程序来计算斐波那契数列。基本上,我想让我的程序计算,比如说,10个斐波那契数,然后计算它们的方差和标准差。目前,我设法得到的程序来计算斐波那契数,但我不知道如何我可以加载这些数字直接计算方差和标准差。我要求输入它们并将它们保存在数组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 wantn" << 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 wantn" << 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();   
} 

不需要为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;

现在对于方差和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;
}

现场演示

最新更新